zero initialization and static initialization of local scope static variable

后端 未结 2 1915
栀梦
栀梦 2020-12-05 03:26

I read several posts on C++ initialization from Google, some of which direct me here on StackOverflow. The concepts I picked from those posts are as follows

2条回答
  •  甜味超标
    2020-12-05 04:17

    I believe there are three different concepts: initializing the variable, the location of the variable in memory, the time the variable is initialized.

    First: Initialization

    When a variable is allocated in memory, typical processors leave the memory untouched, so the variable will have the same value that somebody else stored earlier. For security, some compilers add the extra code to initialize all variables they allocate to zero. I think this is what you mean by "Zero Initialization". It happens when you say:

     int i; // not all compilers set this to zero
    

    However if you say to the compiler:

     int i = 10;
    

    then the compiler instructs the processor to put 10 in the memory rather than leaving it with old values or setting it to zero. I think this is what you mean by "Static Initialization".

    Finally, you could say this:

     int i;
     ...
     ...
     i = 11;
    

    then the processor "zero initializes" (or leaves the old value) when executing int i; then when it reaches the line i = 11 it "dynamically initializes" the variable to 11 (which can happen very long after the first initialization.

    Second: Location of the variable

    There are: stack-based variables (sometimes called static variables), and memory-heap variables (sometimes called dynamic variables).

    Variables can be created in the stack segment using this:

    int i;
    

    or the memory heap like this:

    int *i = new int;
    

    The difference is that the stack segment variable is lost after exiting the function call, while memory-heap variables are left until you say delete i;. You can read an Assembly-language book to understand the difference better.

    Third: The time the variable is initialized

    A stack-segment variable is "zero-initialized" or statically-initialized" when you enter the function call they are defined within.

    A memory-heap variable is "zero-initialized" or statically-initialized" when it is first created by the new operator.

    Final Remark

    You can think about static int i; as a global variable with a scope limited to the function it is defined in. I think the confusion about static int i; comes because static hear mean another thing (it is not destroyed when you exit the routine, so it retains its value). I am not sure, but I think the trick used for static int i; is to put it in the stack of main() which means it is not destroyed until you exit the whole program (so it retains the first initialization), or it could be that it is stored in the data segment of the application.

提交回复
热议问题