What is the result of running the following code?
package com.test;public class Inc { public static void main(String[] args) { Inc inc = new Inc(); int i = 0; inc.fermin(i); i = i++; System.out.println(i); } void fermin(int i) { i++; }}The result is: 0
The result of running the above similar code in C/C++ is: 1. Why is this?
This is because Java uses an intermediate cache variable mechanism:
i=i++; equivalent to:
temp=i; (i on the right side of the equal sign)
i=i+1; (i on the right side of the equal sign)
i=temp; (i on the left side of the equal sign)
And i=++i; is equivalent to:
i=i+1;
temp=i;
i=temp;
Detailed explanation:
There are two storage areas in jvm, one is the temporary storage area (a stack, called the stack below), and the other is the variable area.
jvm will run this statement like this:
Step 1 jvm copy the value of i (its value is 0) to the temporary variable area (temp=0).
Step 2 Add the value of variable area i to 1, and the value of i is 1.
Step 3 Return the value of the temporary variable area (temp). Note that this value is 0 and has not been modified.
Step 4 The return value is assigned to i in the variable area, and the value of i is reset to 0.
There is no other temporary variable or temporary space to save i in c/c++. All operations are completed in one memory space, so it is 1 in c/c++.
The above introduction to the self-increase problem in Java is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.