Search code examples
javacpostfix-notation

adding variable to itself with postfix increment different in Java/c# than in C


In Java and C# if I do this:

int i=1;
int j= i++ + i;

j is 3, i.e. it translates to 1+2 and increments i before the addition.

However, in C j is 2, i.e. it translates to 1+1 then increments i.

What is the internal mechanism in C and Java/C# that causes this difference in what an expression is?

(the same goes for post-fix. Java/C# become 4 and C becomes 3.)

thanks.

Btw, initially I assumed it would be what the C answer was and so was confused by the Java/C# result.


Solution

  • Unlike Java and C# which specify precisely when the side effects would take place, C prohibits the use of an expression with side effects before the next sequence point. Not only does your expression produce a different result in C, but it is also undefined behavior.