the following snippet gives different outputs in c++ and java: int i = 0; i = i++; i = i++; i = i++; i = i++; System.out.println("i = " + i);//output is: i = 0 //printf("i = %d" + i);//output is: i = 4 why is this difference in outputs? i will appreciate if anyone can point this difference in behaviour (specially if java syntax is based on c/c++).
Sandeep, Use prefix increment instead of postfix increment operator and we can get the output in java. int i=0; i = ++i; i = ++i; System.out.println("i = "+i); the above code snippet will give the result of i = 2 Here the difference is obvious from the difference between post fix and prefix operators..
Let me try to explain why the post fix operation is not working Refer to the JLS 15.13.2 Postfix increment operator ++ "PostfixExpression ++" The result of the postfix increment expression is not a variable, but a value. At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Refer to JLS 15.25 Assignment operators "LeftHandSide AssignmentOperator AssignmentExpression" At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable. Based on the above, In the first instance the assignment expression was i++, and the left hand side (i) is assigned with a value of 0 before the postfix increment. Once the assignment has occured Since i is already assigned with a value and the postfix operator is trying to operate on the same (which is a value and not a variable) the postfix operation fails. whereas in the case of prefix increment the increment occurs before the assignment. There are some differences between the parsers used for c++ and java which i am afraid is too much for me to digest!! I hope i have not confused you. Kalidas.