0

I have seemingly very basic question about the order of operations in c, specifically involving the increment operator.

If I have this code:

int x,y;
y = 4;
x = ++y + y--;

printf("x: %d y: %d", x,y)

The output I expect is:
x: 10 y: 4

I got this using the process described here:
http://ntci.on.ca/compsci/java/ch2/2_3.html
(See Example 2, in the red box)

When I run this in eclipse on Mac with the MacOSX GCC, this is the answer it gives. Great.

However, when I use CLion (under MinGW), it gives:
x: 9 y: 4

So does Code::Blocks (with MinGW), and many online compilers such as:
https://www.onlinegdb.com/online_c_compiler
and
jdoodle's
and
tutorialspoint's.

What gives? Is eclipse and my understanding of the order of operations in C wrong?

Or are CLion, Code::Blocks, and a ton of online compilers wrong?

  • The compilers are fine. It's undefined behavior. – Fred Larson Oct 18 '17 at 21:48
  • Why would you want to increment and decrement a value in the same expression anyway? – Weather Vane Oct 18 '17 at 21:49
  • @WeatherVane I can think of some funny applications when it's some hardware register... – Eugene Sh. Oct 18 '17 at 21:50
  • 1
    In this case, different compilers are free to translate the same thing differently, because the C standard does not define the order in which the operands are evaluated. In other words, never do this, at best it's a bug waiting to happen. A new compiler release, different optimization setting, etc. could suddenly cause the behavior to change. – Tom Karzes Oct 18 '17 at 22:06
  • All of the examples I have found involve assigning a variable to itself, with the increment operator. Like `i = i++ + --i`. It's good to know that this applies in general! – Troy Giorshev Oct 18 '17 at 23:18
  • 1
    The description page you cited is about Java. Java has well-defined rules for expressions like this, but C does not. In C, this expression is *undefined*, specifically because it tries to modify variable `y` twice. – Steve Summit Oct 19 '17 at 02:03

0 Answers0