Problem with post and pre increment

This question may be easy for yall, but im really confused with the answer

The code is like that
  int x = 1, y;
  y = --x + ++x + x-- + --x - --x + ++x + x++ - --x + x--;

the answer is supposed to be x = -2, y = 4 ( when i complied it in eclipse)

But I only get x = -2, y = 1 when i do it with pen.

Can anyone tell me how it works out?
This expression is undefined in C and in C++. It has no "right" answer whatsoever: the language assumes that you, the programmer, never attempt to modify the same variable twice in the same expression (without sequencing, which you don't have here)


PS: Although the program with an explicitly undefined expression is meaningless, it's fun to watch things burn.. here's what the compilers I have around produced:

linux/gcc: x = -2 y = 4
linux/clang: x = -2 y = 1
aix/gcc: x = -2 y = 4
aix/xlc: x = -2 y = 3
solaris/sun: x = -2 y = -5

Last edited on
Thanks a lot, cubbi.

Reckon is going the same case in java as well is it?
Last edited on
Undefined behavior exists in C-based languages because the designers of C wanted it to be an extremely efficient low-level programming language. In contrast, languages like Java (and many other 'safe' languages) have eschewed undefined behavior because they want safe and reproducible behavior across implementations, and willing to sacrifice performance to get it. While neither is "the right goal to aim for," if you're a C programmer you really should understand what undefined behavior is.
- Chris Lattner, in LLVM project blog
Topic archived. No new replies allowed.