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

1

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?

Scevour answered 17/10, 2011 at 6:38 Comment(2)
which compiler do you use? the same code gives m=4 and n=6 for me (Visusal Studio 2010)Morningglory
It's because you can't change the same variable twice in a statement without sequencing point. That causes undefined behavior in C.Masera
B
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).

Bower answered 17/10, 2011 at 6:43 Comment(4)
"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.Basalt
@EJP: Such a program is not correct.Bower
if such a program is not correct the compiler shouldn't compile it.Basalt
@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.Bower

© 2022 - 2024 — McMap. All rights reserved.