+ 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; }
5 Antworten
+ 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.
+ 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.
+ 1
Thx~
+ 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.
0
Kit D. Cat ok