0
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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Josh Morrison
  • 7,488
  • 25
  • 67
  • 86
  • See: http://stackoverflow.com/questions/1895922/sequence-points-and-partial-order (question assumes knowledge of sequence points) and http://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept (see accepted answer). Not *exact* duplicates, but this UB is "well covered" in SO. –  Jan 26 '11 at 22:43
  • See also [Undefined Behavior and Sequence Points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). It's from the "c++-faq" but still applies in general. –  Jan 26 '11 at 22:50

4 Answers4

7

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

It's undefined behaviour - so you can get any answer you'd like.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
0

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.

Artyom Shalkhakov
  • 1,101
  • 7
  • 14
-1

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.

Ron
  • 2,215
  • 3
  • 22
  • 30
  • 1
    xor 0 with 0 is actually _0_. `0,0->0, 0,1->1, 1,0->1, 1,1->0`. That's not a good start to an answer :-) – paxdiablo Jan 26 '11 at 23:02