What actually compiler does when we declare static variables?

后端 未结 4 1609
既然无缘
既然无缘 2021-01-05 07:58

I want to know what actually going under the hood,how compiler treats static variables. Unlike auto variable, static variable\'s value persist even after the end of block bu

4条回答
  •  情深已故
    2021-01-05 09:04

    This code:

    void function()
    {
        static int var = 6;
    
        // Make something with this variable
        var++;
    }
    

    is internally similar to this:

    int only_the_compiler_knows_this_actual_name = 6;
    
    void function()
    {
        // Make something with the variable
        only_the_compiler_knows_this_actual_name++;
    }
    

    In other words, it's a kind of "global" variable whose name, however, doesn't conflict with any other global variable.

提交回复
热议问题