Transferred from: http://blog.csdn.net/maggiedorami/article/details/7986098
Let's look at a program like this:
- 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);
- }
The result of this operation is:
[Java]View Plaincopy
- sum1=1
- sum2=3
And I write the same logic code in C, and I get different results:
[CPP]View Plaincopy
- 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 ();
- }
The result of this operation is:
[CPP]View Plaincopy
- Sum1=0
- Sum2=4
This differs because in C, each variable can have only one unique value at each point in its life cycle. As a result, the contents of the corresponding memory area of the variable are rewritten at each increment operation.
In Java, sum1= (i++) + (i++) is executed, and 2 temporary integer variable objects are created to store the results of each self-increment operation.
Java uses the mechanism of this intermediate cache variable.
Then look at the programmer interview a very classic example:
[Java]View Plaincopy
- Public static void Main (string[] args) {
- Int J = 0;
- For (int i = 0; i < ; i++)
- J = j + +;
- System.out.println (j);
- }
For Java, the output value of j is 0.
Because the middle cache variable mechanism of Java causes the j=j++ statement to be decomposed into the following actions:
[Java]View Plaincopy
- temp = j;
- j = j + 1;
- j = temp;
Individuals feel that this use of self-growth is not good, should be in complex statements to avoid the use of post-increment (self-subtraction).
In addition, it is worth noting that some languages that use the mechanism of intermediate cache variables, the output is not necessarily 0. For example, when C + + has a post-increment operation on some basic types and pointer types, the compiler will omit intermediate cache variables.