int a =10;
if (++a == a++)
{
cout << a++ << endl;
cout << ++a << "\t "<< a++<< endl;
}
cout << a << endl;
I can't figure out why the output is
___________
12
15 13
15
_________
shouldn't it be
___________
12
14 14
15
_____________
Can some one explain this to me?? I know that my problem is in understanding the priority of execution (output vs. increament) in the secon "cout" statement.
I had fun playing with this because I had no idea how this worked lol.. but you can figure it out from this website and also throwing in some
"cout << a << endl;" everywhere
That is very easy. It is undefined behaviour. It is ok by the standard, if the compiler turns this code into instructions that detonate the Moon into tiny pieces.
The link by Sanction writes:
Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of sequencing rules.
Well I just found this: http://en.cppreference.com/w/c/language/eval_order
"Order of evaluation of the operands of any C operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below). The compiler will evaluate them in any order, and may choose another order when the same expression is evaluated again."
Have you tried to run the program several times? If there are different results, this may be the explanation.
Have you tried to run the program several times? If there are different results, this may be the explanation.
There won't, because:
The compiler will evaluate them in any order
The compiler has created the necessary instructions in some order and that order is now fixed and in the binary. Recompile with different compiler or with different compiler options and then perhaps the order is different (but equally undefined).