0

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

int i = 10;
int n = i++*5*i;

Output

value of n = 550 (in Java) value of n = 500 (in C and C++ )

Why not same result? Why different?

Community
  • 1
  • 1
Anand
  • 9
  • 1

3 Answers3

5

In Java, this is a well defined operation. It will:

  1. increment i (it's now 11);
  2. Produce the old value of i (10), because you used the postfix increment operator;
  3. Multiply that by 5 (10*5 = 50);
  4. Multiply that by the current value of i (50*11 = 550);

In both C and C++ this operation has undefined behaviour, so anything could happen. If anything could happen, that explains the results, whatever they are, and whether they make sense to you or not.

Community
  • 1
  • 1
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
2

In C and C++, operations such as:

j = i++ + i;

are undefined, due to lack of sequence points. In Java, they are well defined. Therefore, you could see a difference in results.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Forgive me for nitpicking, but that's not a correct use of "therefore" - he could easily have seen the same results, they just happened to be evaluated in a different order. In other words, '550' could well be output by the C++ code. – Arafangion Sep 16 '11 at 00:20
  • I thought that the operators were handled with same priorities in C C++ and Java but it seems that Java handles differently. In the context of JAVA ++ has more high priority than % as documentation http://w3i.in/754 int i = 10; int n = i++*5*i; in this case i++ is done but if expression is as follows: int i = 10; int n = i++*5; then i++ is handled after multiplication even though multiplication has lower priority. why? – Anand Sep 16 '11 at 00:21
  • 3
    @Arafangion: "Therefore" seems fine to me. The first sentence is a statement; the second statement is the conclusion. (Note that I was careful to say "could", not "will".) – Oliver Charlesworth Sep 16 '11 at 00:22
  • @Anand: It's nothing to do with operator precedence. – Oliver Charlesworth Sep 16 '11 at 00:22
  • 2
    @Anand it's not possible to reason about this in terms of operator precedence. You must understand what a [sequence point](http://en.wikipedia.org/wiki/Sequence_point) is. – Karl Knechtel Sep 16 '11 at 00:38
0

Because what you are doing is undefined. The increment operator should not be placed in expressions of assignment with the variable being incremented.

i = i++; //undefined
n = i++ + i; // also undefined
zellio
  • 31,308
  • 1
  • 42
  • 61