Re: output?
On Aug 7, 3:18 am, Anubhav <rkld...@gmail.com> wrote:
int& f(){
static int x = 0;
x++;
return x;
}
int main(){
int x = 0;
f() += 1;
f() = f() + 1;
cout << f();
}
What should be the output of the code shown?
VS gives 5 and gcc gives 6.
Both are correct. Everything is simple up to the expression that calls
f twice.
The order of evaluation around assignment isn't specified, so the
compiler could execute the lhs call, increasing x to 3 and yielding a
reference, then execute the rhs call, increasing x to 4, fetch x, add
1 and assign back to the reference to yield 5.
Or it could execute the rhs call, increasing x to 3 and yielding a
reference, then fetch the value there, add 1 to get 4, then execute
the lhs call, increasing x to 4, and assign the 4 for the previous
computation.
There are some other valid execution orders, but those two should be
enough to illustrate the issue.
Sebastian
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]