So this question is basically guess the output program. I will be specific.
What I understood is value of x
is passed by reference to y
, which means whatever changes we do on x
is reflected on y
and vice versa. In line 6 we pass the value of x
to y
by pass by reference.
In line 7, x
is incremented, so x
becomes 11 and so does y
. Now I expected the output to be 11 11
, because we are printing x
first, so x
which was 11 will be printed , and as of y
, it is post increment so 11 will be printed first and then only y
is incremented. But I was wrong(obvious) the answer was 12 11
.
I tried debugging and it didn't explain why it happened either. After some googling, I found that there is something called cout
rule where execution of cout
statement happens from right to left, which means in line 8, due to post increment y
is printed first, and then incremented so x
gets changed and becomes 12. But again the output in that case is 11 12
and not 12 11
. Please can you explain if the cout
rule is really true and if yes can you explain how is it really done or there is something else to this? Thanks.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int &y = x; // line 6
x++; // line 7
cout<< x << " " << y++; // line 8
return 0;
}