+ 1

C++: Questions about pass by reference

Why the output is 57? Can someone pls explain to me...int &y = x will pass the x value to y by reference right?Thats mean at that point, y=0. And then y = 5. And x still equals to 0. Am i right? #include <iostream> using namespace std; int main() { int x=0;int &y=x;y=5; while(x<=5){ cout<<y++; x++; } cout<<x; return 0; }

23rd Nov 2019, 10:52 AM
汝風留名
汝風留名 - avatar
5 odpowiedzi
+ 4
汝風留名 when x and y are referring to the same memory then if value at y is changed, it means that even value at x will change. So 5<=5 is true and y++ = 5 is printed. But now y is 6 and x++ is done. So when while loop checks for condition again now x is 7. So condition fails and 7 is printed. Thus your output 57.
23rd Nov 2019, 11:15 AM
Avinesh
Avinesh - avatar
+ 1
The last run of the loop will be when x (which is also y) is 5. After it is couted, it will be upped two times (y++, x++), so it ends up at 7.
23rd Nov 2019, 11:00 AM
HonFu
HonFu - avatar
+ 1
Thx~
23rd Nov 2019, 11:18 AM
汝風留名
汝風留名 - avatar
+ 1
Kit D. Cat Oh, that’s cool. Does “int &y = x;” work in C as well? Does it work for function calls? If so, that could be useful so I don’t have to pass a pointer and dereference it whenever I need to use it.
23rd Nov 2019, 8:50 PM
Jason Stone
Jason Stone - avatar
23rd Nov 2019, 10:30 PM
Jason Stone
Jason Stone - avatar