It is obvious that first cout prints 7 7 but why the second one prints 8 8 7 ? Why not 7 8 8? How does such constructions work in c++?
int ink(int *x){
*x += 1;
return *x;
}
int main(){
int *a;
int b = 6;
a = &b;
cout << ++b << " " << b << endl;
cout << b << " " << ink(a) << " " << b;
return 0;
}
Because the code contains side effects. You can’t be sure in what order the elements will be executed.
Here is some more info:
http://en.wikipedia.org/wiki/Sequence_point
EDIT: Here is the output on my machine:
7 6
8 8 7
As you can see it’s different from yours. The correct approach is to make all calculations before the cout and then pass the values only.
It may be easier to understand what’s going on if you look at the chain of function calls that the second one devolves to (I’m using the operator defs here, which do match the gcc headers on my system):
cout << b << " " << ink(a) << " " << b;
operator<<(operator<<(cout.operator<<(b)," ").operator<<(ink(a)), " ").operator<<(b);
Aside: This looks very odd because the numeric inserters are all methods of the object, while the character string inserters are all global functions, which makes the call order even more strange than it might be.
Now that you have the actual call chain, you can see how it would end up putting the 7 on the stack before the ‘ink’ call, but actually won’t use that until well after, thus causing the non-intuitive outputs.