5

Consider:

int m = 2, n;

n = m++ + (++m);

In C output is:

m = 4, n = 4;

In Java output is:

m = 4, n = 5;

How does this happen?

phoxis
  • 60,131
  • 14
  • 81
  • 117
  • which compiler do you use? the same code gives m=4 and n=6 for me (Visusal Studio 2010) – codencandy Oct 17 '11 at 06:43
  • It's because you can't change the same variable twice in a statement without sequencing point. That causes undefined behavior in C. – Daniel Oct 17 '11 at 06:45

1 Answers1

9

It can differ because C does not allow a correct program to contain such an expression - C does not define the behaviour of such a program. This gives C compilers wide latitude in how they interpret such expressions.

Java more tightly constrains implementations by defining the expected behaviour of expressions like this.

(The rule that this breaks in C is that an expression may not modify the value of an object more than once without an intervening sequence point).

caf
  • 233,326
  • 40
  • 323
  • 462
  • 1
    "C does not allow a correct program to contain such an expression." Yes it does; it just doesn't specify its behaviour. Not the same thing. – user207421 Oct 17 '11 at 09:04
  • @EJP: Such a program is not correct. – caf Oct 17 '11 at 13:11
  • if such a program is not correct the compiler shouldn't compile it. – user207421 Oct 17 '11 at 21:21
  • @EJP: A conforming compiler *is* allowed to reject the program in the example. However, C compilers are not *required* to diagnose this particular error because doing so can be impossible at compile-time: consider `(*p)++ + (*q)++)`, which is OK as long as `p != q`. – caf Oct 17 '11 at 21:30