I have a variable declared like this:
int j=0;
When I write:
cout<<j++<<" "<<j++<<" "<<j++<<"\n";
I receive this output:
2 1 0
I expect to receive this output:
0 1 2
Could you explain the result?
I have a variable declared like this:
int j=0;
When I write:
cout<<j++<<" "<<j++<<" "<<j++<<"\n";
I receive this output:
2 1 0
I expect to receive this output:
0 1 2
Could you explain the result?
this is confusing but normal because order of evaluation for this operator is right to left.
The spec says that if you modify the same variable more than once within the same sequence point, the result is "undefined".
Sequence points are between ; (and also , is a sequence point, not sure if there are others).
What you're trying is the same as the better known trivia question, "what's the value of x after the second assignment?"
int x;
x = 0;
x = x++;
The answer is "undefined".
This is because your compiler is likely evaluating the equation from right to left.
check out this question for more info.
Edit: Tested on g++ 4.4.0
#include <iostream>
int main (int argc, char **argv) {
int j = 0;
std::cout << j++ << " " << j++ << " " << j++;
return 0;
}
[john@awesome]g++ rtl.cpp -o rtl [john@awesome]./rtl 0 1 2 [john@awesome]
This code is equivalent to
... operator<<( operator<<( operator<<( operator<<(cout,j++), " " ), j++ ), "\n" ); ...
Though order of function call is given, order of parameters evaluation is not. So there is no guarantees which j++ is evaluated first. There are modifications of j without sequence points between them, so you see result of Undefined Behaviour.
[Edit1] There is inaccuracy in previous. operator<<(int) is a member function of basic_ostream. Denote operator<<(int) as f, operator<<(ostream&,const char*) as g. Then we have
...g(f(j++)," ").f(j++)...
Order of evaluation still can be: eval(j++) -> eval(j++) -> sequence point -> call(f) -> sequence point -> call(g) -> sequence point -> call(f). This is because of following quote from standard [expr.4]:
Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified