Let's look at a program like this:
[Java]
Public static void main (String [] args ){
Int I, sum1, sum2;
I = 0;
Sum1 = (I ++) + (I ++ );
System. out. println ("sum1 =" + sum1 );
I = 0;
Sum2 = (++ I) + (++ I );
System. out. println ("sum2 =" + sum2 );
}
Its running result is:
[Java]
Sum1 = 1
Sum2 = 3
However, I use C language to write code with the same logic to get different results:
[Cpp]
Void main ()
{
Int I, sum1, sum2;
I = 0;
Sum1 = (I ++) + (I ++ );
Printf ("sum1 = % d \ n", sum1 );
I = 0;
Sum2 = (++ I) + (++ I );
Printf ("sum2 = % d \ n", sum2 );
Getchar ();
}
Its running result is:
[Cpp]
Sum1 = 0
Sum2 = 4
This is different because in C language, each variable can have only one unique value at each time point in its lifecycle. Therefore, during each auto-increment operation, the content of the memory region corresponding to the variable is overwritten.
In java, sum1 = (I ++) + (I ++) is executed. Two temporary integer variable objects are created to store the results of each auto-increment operation.
Java uses this intermediate cache variable mechanism.
Let's look at a classic example in the programmer's interview book:
[Java]
Public static void main (String [] args ){
Int j = 0;
For (int I = 0; I <100; I ++)
J = j ++;
System. out. println (j );
}
For java, the output value of j is 0.
Because java's intermediate cache variable mechanism enables j = j ++ statements to be split into the following operations:
[Java]
Temp = j;
J = j + 1;
J = temp;
I personally think it is not good to use auto-increment in this way. We should avoid using post-auto-increment (auto-increment) in complicated statements ).
In addition, it is worth noting that some languages adopt the intermediate cache variable mechanism, and the output is not necessarily 0. For example, when C ++ performs post auto-increment operations on some basic types and pointer types, the compiler will save the intermediate cache variable operations.