C # static variable assignment problem

Source: Internet
Author: User

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

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.