Suraj: "undefined behaviour" includes "normal behaviour that you might expect in some cases" as well as "slightly strange behaviour". ;)
The point is: The compiler is allowed to make a couple of instruction reordering and optimizations with your code that you might not expect from your "normal" gut feeling.
So taken
|
i = (11 == i) ? i++ : i--;
|
the compiler could decide that its faster for him to first assign the right hand value of the = operation to i and
after this, do the increment operation on i++.
It is allowed to do such reordering, because it got the blessing from the C++ standard, that no expression writes on the same variable twice. (Or if you do write twice like in the current example, its "undefined behaviour", which means it is OK for the compiler to generate code that do the strange behaviour you see as "errorornous").
And that's the punch line why you should never allow "undefined behaviour" in your code, even if it "seems working". It could even change the behaviour when you twich a couple of compiler options (like using "optimize for size" instead of "optimize for speed"). It could even change behaviour when just compiled the same code multiple times (although that's rather rare. Indeterministic compiler behaviour is still a very seldom thing to see ;))
i = (i = 1)+ 1 will give u 2.. and that's correct. |
Nope, it gives you "undefined behaviour", which may be 2 for your compiler in your current optimization settings on your current platform most of the times. But still it could lead to a crash and the compiler can still be labelled "working correct according to the C++ standard".