In line 2 the compiler starts the processing (or whatever its called, if its something else do tell me) from the right side (do tell me why? Can't recall it).
Now the value of x is updated to 11 since its pre-increment and in the second half the value of x remains the same i.e. 11 since its post-decrement.
Please tell me what the compiler does next ? (step-by-step).Does it go processing all the way to right again (if so why? I ask this because it does not do so for other statements so how does it know to do it here)or something else ?
I know that the output will be 22 in this case.I just want to know the behaviour of compiler.
Kindly excuse bad English.I don't know much about it.
Thanks.
The compiler starts always on the left side.
It does not mean y equals x++ + ++x.
First the compiler sees the integer y then
assigns the addition of x++ + ++x to y.
The x++ is first incremented (11), ++x (still 11)
is incremented after the addition.
Let´s test it:
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream>
usingnamespace std;
int main()
{
int x=10,y;
y=x++ + ++x;
cout << y << endl;
cout << x << endl;
return 0;
}
The expression x++ + ++x is an error in C++ (and in C, for that matter) because it attempts to modify the same object (x) twice between sequence points.
The two arguments of + (the x++ and the ++x) will be evaluated unsequenced: left before right, right before left, or simultanously (e.g. by interleaving the CPU instructions). Both arguments will attempt to write to x. The compiler will always expect that the two arguments are accessing different objects and will not suspect foul play on your part. If you attempt to modify the same object twice, the compiler is within its rights to crash and burn. It is the same as accessing an array out of bounds.
In practice all compilers I've seen produce some values when given such erroneous expressions to compile, but the values are unpredictable.
I'll test a few:
gcc 4.6.2 on linux: x = 12 y = 22
gcc 3.4.6 on sparc: x = 11 y = 21
Visual Studio 2010 on windows: x = 12 y = 22