Unexpected output of a Call-by-Reference

Dec 17, 2013 at 8:19am
In the code below, the function will be first executed, producing the following data
x = 15
y = 11
x+y = 26

as there is a "&" operator in front of x, so the value of x will be changed to 15.

I expect the result as
26
15
10

But the program give me
26
5
10

What's wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int function(int& x, int y)
{
	x = x+y;
	y++;
	return x+y;
}

int main()
{
	int x = 5, y(10);
	cout << function(x,y) << endl << x << endl << y << endl;

	return 0;
}
Last edited on Dec 17, 2013 at 8:21am
Dec 17, 2013 at 8:49am
The order of evaluation for arguments to the chained operator<< are not specified.

Try:

1
2
    cout << function(x,y) << endl ;
    cout << x << endl << y << endl ;
Dec 17, 2013 at 8:57am
the problem is the order of evaluation. You expect that function() is executed first, but in fact it starts with the last expression
Last edited on Dec 17, 2013 at 8:57am
Dec 17, 2013 at 8:59am
but in fact it starts with the last expression

Do you mean that the computer read from right to left?
Dec 17, 2013 at 9:53am
Do you mean that the computer read from right to left?


It may begin with the last. It may begin with the first. It may begin with the middle. The order is unspecified, so the compiler is perfectly correct in whatever order it takes.
Topic archived. No new replies allowed.