-3

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;
}
  • The reason I believed for my output was that even though the y had an & sign, I thought that y was aliasing x and thus x and y were both set to 0 until they get incremented and would yield an output of x = 1 and y = 1 but instead outputted x = 2 and y = 2. – 73memedream Sep 12 '17 at 23:07
  • 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 then x becomes 2. And because y represents x, when you call y it calls x and you see 2 again. – ssovukluk Sep 12 '17 at 23:09
  • 1
    @73memedream, You said it. `y` is aliasing `x`. The behaviour you describe is what happens if `y` is a copy of `x`. – chris Sep 12 '17 at 23:10
  • OHHHH! I get it now. Wow I'm dumb...thank you @ssovukluk – 73memedream Sep 12 '17 at 23:12
  • `y` is just an alias name to `x`, They do refer to the very same address in memory, with different names only. So what affects the one affects the other. In fact they are the same. – Raindrop7 Sep 12 '17 at 23:13
  • @73memedream not dumb, just unfamiliar (:-) Now you know about references. – Kevin Anderson Sep 13 '17 at 01:28

2 Answers2

1

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.

ssovukluk
  • 438
  • 3
  • 14
0

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.
idler1515
  • 150
  • 3
  • 11