classProgram {Static inti =Getnum (); intj =Getnum (); Static intnum =1; Static intGetnum () {returnnum; } Static voidMain (string[] args) {Console.WriteLine ("i={0}", i); Console.WriteLine ("j={0}",NewProgram (). j); Console.read (); } }
The output value is
I=0
J=1
Analyze the above code :
Console.WriteLine ("I={0}", i);
Here I is the static variable, and the first time the class program is loaded, the memory is allocated to all the static variables in the program. Although Hyper-Threading technology is now in order, the instructions are logically and sequentially executed from top to bottom, so allocate memory for the static int I, and leave the default value of int 0 in that memory, and then allocate memory for the static int num variable, and the value is of course 0.
Then the second step, assign a value to the variable: first assign the static int i variable, i=getnum (), see the code inside the Getnum (), is the return num, this time num value is 0, so i=0. The variable num is then assigned a value, num=1, and Num is 1 after this line of code executes. So, j=1.
So the final result is:
I=0 j=1
Attention:
When a class is loaded for the first time, the static variables in the class are allocated memory space sequentially, and after allocating all the memory space, the static variables are assigned sequentially.
First divided into two parts registers and memory (including cache)
Memory is divided into two parts code and data
Data is divided into two parts static storage and Runtime storage
Runtime storage is divided into stacks and heaps
Static storage is divided into global static storage and constants
C # static variable assignment problem