问题
I'm running the following programs in Visual C++ and Java:
Visual C++
void main()
{
int i = 1, j;
j = i++ + i++ + ++i;
printf("%d\n",j);
}
Output:
6
Java:
public class Increment {
public static void main(String[] args) {
int i = 1, j;
j = i++ + i++ + ++i;
System.out.println(j);
}
}
Output:
7
Why the output in these two languages are different? How both the langauges treat pre and postincrement operators differently?
回答1:
In C/C++ behavior is undefined because In this expression i
is modified more then once without an intervening sequence point. read: What's the value of i++ + i++?
Of-course in Java behaviour of this kind of codes is well defined. Below is my answer for Java, step by step:
At the beginning i
is 1
.
j = i++ + i++ + ++i;
// first step, post increment
j = i++ + i++ + ++i;
// ^^^
j = 1 + i++ + ++i;
// now, i is 2, and another post increment:
j = i++ + i++ + ++i;
// ^^^^^^^^^
j = 1 + 2 + ++i;
// now, i is 3 and we have a pre increment:
j = i++ + i++ + ++i;
// ^^^^^^^^^^^^^^^^
j = 1 + 2 + 4;
j = 7;
回答2:
The C++ example evokes undefined behavior. You must not modify a value more than once in an expression. between sequence points. [Edited to be more precise.]
I'm not certain if the same is true for Java. But it's certainly true of C++.
Here's a good reference:
Undefined behavior and sequence points
来源:https://stackoverflow.com/questions/17514805/behaviour-of-preincrement-and-postincrement-operator-in-c-and-java