Problem with post and pre increment

Sep 19, 2013 at 2:03pm
This question may be easy for yall, but im really confused with the answer

The code is like that
1
2
  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?
Sep 19, 2013 at 2:29pm
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)

See http://en.cppreference.com/w/cpp/language/eval_order

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 Sep 19, 2013 at 2:34pm
Sep 20, 2013 at 6:09am
Thanks a lot, cubbi.

Reckon is going the same case in java as well is it?
Last edited on Sep 20, 2013 at 6:09am
Sep 20, 2013 at 6:46am
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

http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
Topic archived. No new replies allowed.