Auto-increment operators and intermediate cache variables in Java

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.