1

In c :

int a = 33;
a = a++;
printf("\n\t a :%d",a); // it'll print 34

In Java :

int a = 33;
a = a++;
System.out.printf("\n\t a :%d",a); // it'll print 33

Why the post increment works correctly in C and why not in Java?

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59
  • 9
    http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc - the C part is undefined behavior, you can't rely on it (could print anything). The Java part is as per Java spec, i.e. the result you see is the expected behavior. – Mat Mar 10 '13 at 19:00
  • In `C`, the code you posted has undefined behavior. It does not "work correctly" because there is no definition of correct behavior for that code! Although in your environment it prints 34, in others it will print 33. – Ted Hopp Mar 10 '13 at 19:03
  • http://stackoverflow.com/questions/11570589/java-i-operation-explanation - for the Java part – Mat Mar 10 '13 at 19:04
  • Because they're different languages. Where does it say they must be the same? – user207421 Mar 10 '13 at 23:24

1 Answers1

3

Good question.

There's a difference between a++ and ++a. In Java (at least), each will increment the variable, but the value represented by the expression is different.

int i = 0;
System.out.println(i++); // 0

int j = 0;
System.out.println(++j); // 1

So you're incrementing a by 1, but then setting it back to the original value.

From the Java Tutorial:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

wchargin
  • 15,589
  • 12
  • 71
  • 110
  • 1
    Is this really necessary? It's been answered many times before on the site, and instead you should have flagged the question as a duplicate. – Richard J. Ross III Mar 10 '13 at 19:03
  • 4
    This does not really answer OP's question, which is why there appears to be a difference between C and Java. – Ted Hopp Mar 10 '13 at 19:05