int x = 0;
x^=x || x++ || ++x;
and the answer for x at last is 3. How to analysis this expression? little confused about this. Thanks a lot.
int x = 0;
x^=x || x++ || ++x;
and the answer for x at last is 3. How to analysis this expression? little confused about this. Thanks a lot.
This is undefined behaviour. The result could be anything. This is because there is no sequence point between the ++x
and the x ^=
, so there is no guarantee which will be "done" first.
As others have already noted, this is undefined behavior. But why?
When programming in C, there is an inherent difference between a statement and an expression. Expression evaluation should give you the same observable results in any case (e.g., (x + 5) + 2 is the same as x + (5 + 2)). Statements, on the other hand, are used for sequencing of side-effects, that is to say, will generally result in, say, writing to some memory location.
Considering the above, expressions are safe to "nest" into statements, whereas nesting statements into expressions isn't. By "safe" I mean "no surprising results".
In your example, we have
x^=x || x++ || ++x;
Which order should the evaluation go about? Since || operates on expressions, it shouldn't matter whether we go (x || x++) || ++x or x || (x++ || ++x) or even ++x || (x || x++). However, since x++ and ++x are statements (even though C allows them to be used as expressions), we cannot proceed by algebraic reasoning. So, you will need to express the order of operations explicitly, by writing multiple statements.
XOR 0 with 0 is 0. Then ++ twice is equal to 2. Nevertheless, as pointed in other answers, there's no sequence point. So the output could be anything.