Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why output differs in C and Java in the expression m++ + (++m) [duplicate]

Tags:

java

c

expression

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?

like image 425
phoxis Avatar asked Oct 17 '11 06:10

phoxis


1 Answers

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

like image 169
caf Avatar answered Sep 28 '22 14:09

caf