Anything. Literally anything. This code contains undefined behavior and it is allowed to do literally anything. It might format your hard drive and you will nothing to complain about.
Anyone telling otherwise should be smacked in the face by IS printout.
You happens to get 21.
I get 19. Or 21. Or 20. Or 0. Depending on compiler keys, computer I compile on, compiler and moon phase.
The only correct answer is "undefined". And nobody shold write code like that because it is unpredictable and fragile. (also void main() is illegal too, configure your compiler properly if it still allows that)
As I told, it is undefined behavior. Anything could happen. There are no restrictions on value of x, because what you doing is not allowed in strictly conforming C++ code.
You already seen how fragile such constructs: aliitle change in code and they give you different answer. So stop trying to predict what will happen and just do not do that.
Your compiler should warn you about UB here:
warning: operation on 'i' may be undefined [-Wsequence-point]
In your first case compiler happened to applied all side effects before evaluating expression; in second one, it happened to apply them as it evaluated value of corresponding argument.
Thanks for the suggestions..
But its showing same output in all my college workstations
I use borland turbo C++ IDE..
The answer is 18 as
x=(4+1)+(5+1)+(6+1);
Incremented i gets passed to next value of i..
And in first code..the last changed value of i gets adopted in all i's i.e
x=7+7+7;
Therefore,it gives 21
I also do it with
x=++i + ++i;
It gives 12
And with
x=++i + ++i + ++i + ++i;
It gives 32 as output..now what to say..
Other than that, I suggest to get (I presume, you are using Windows) either Visual C++2013 or Code::Blocks + MinGW. Read documentations on compiler and turn on warnings as high as possible.