C++ Why am I getting this output. (Greenhorn here)

145 views Asked by At

So in the following bit of code, I've been trying to figure out as to why the output of the code comes out to be...

X = 2 and Y = 2

when I originally thought it would be x = 1 and y = 1. I'm still a lil mind boggled with C++ coming into the semester and a little explanation with someone with more knowledge than me on this can hopefully mesh this concept into my head.

int main()
{

    int x = 0;

    int& y = x;

    y++;

    x++;

    std::cout << "x = " << x << " y = " << y << std::endl;
}
2

There are 2 answers

1
idler1515 On BEST ANSWER

key point is what the reference sign meant:

int& y = x;
  1. It represent that you are assigning an alias to 'x', so 'y' is actually sharing the same memory address as 'x' do (physically).

doing

y++;

will change the value inside that memory address, which is shared by both 'x' && 'y'. Same as the operation

x++;

As a result, you did 2 increment on the same memory address with intial value of '0', which the value becomes '2'.

  1. same idea, since both 'x' and 'y' are pointing to that exact same memory address, printing 'x' and 'y' will give you the same value.
0
AudioBubble On

x and y are not different than each other. Reference means the other name of x is y. So when you call y it calls x which means if you increase y it increases x. Then you increase x again and x becomes 2. And because y represents x, when you call y it calls x and you see 2 again.