tags:

views:

43

answers:

1
#include<iostream>
int& f(){
 static int x = 0;
 x++;
 return x;
}

int main(){

  f() += 1; //A

 f() = f() + 1; //B
 std::cout << f();
}

The above code outputs 6 on gcc and 5 on MSVC. Now when I modify A and B to f()=f() I get 5 on both compilers. What is the big deal here? Is the behavior undefined. If yes , why?

+5  A: 

It is undefined, because in this code:

f() = f() + 1;

it is not defined which call to f() happens first.

anon
Don't you think that is unspecified behavior? Is the value of x modified more than once between two sequence points even though we have a function call which in itself is a sequence point?
Samuel
@Samuel OK, unspecified, if you like - I can't be doing with getting into that argument yet again.
anon