-25

Why does Java output 50 while C++ outputs 51 for the same code concept?

int i=5;

i= (++i + ++i + ++i + ++i + ++i + i++);

print i

Java: 50

C++: 51

rink.attendant.6
  • 40,889
  • 58
  • 100
  • 149
Guru
  • 11

1 Answers1

8

The results are different because the lauguages are specified differently.

why java says 50

Because the order of evaluation is defined so in Java. The addition is: 6+7+8+9+10+10 == 50. The final post increment is overwritten by the assignment and has no effect.

while c++ says 51

The shown program has undefined behaviour in C++, so it could have any output. It happened to be 51 in this case. More details in this answer: https://stackoverflow.com/a/4176333/2079303

Community
  • 1
  • 1
eerorika
  • 223,800
  • 12
  • 181
  • 301