Search code examples
c++functionstatic-variables

C++: Static variable declarations in a function


Static variables exist outside of the function, in terms of their memory at least (not scope), right? But one thing that always concerned me, is what happens when I call the function a second time. For instance:

f(){
    static char buffer[256*256];
    stuff(buffer);
}

When I call this function a second time, wouldn't it technically be declaring the variable 'buffer' a second time? Or does it work differently with static variables (as opposed to normal ones) once everything is compiled?

... I sometimes wish there was a chart or something of what a c++ compiler usually turns code into (minus optimizations) so I wouldn't have to bother you fine folks with little questions like this, aha. Thank you in advance!

edit: I know it works like this, I just want to know why though. It's probably something mind numbingly simple...


Solution

  • Static storage duration objects in function scope.

    These objects are created on first use.
    Then destroyed in reverse order of creation (with other static storage duration objects).

    #include <iostream>
    
    class X
    {
        public:
            X(int x): m(x)      {std::cout << "X: " << m << " created\n"; }
            ~X()                {std::cout << "X: " << m << " destroyed\n";}
    
        private:
            int m;
    };
    
    
    static X    x1(1);
    
    int test()
    {
        std::cout << "Test: Start\n";
        static  X x3(3);
    
        std::cout << "Test: Finished\n";
        return 5;
    }
    
    
    int main()
    {
        std::cout << "Main: Start\n";
        X   x2(2);
    
        test();
    
        X   x4(4);
        std::cout << "Main: Finished\n";
    }
    

    Now Try it: (comments added). SSDO => Static Storage Duration object.

    g++ X.cpp
    ./a.out
    X: 1 created    // SSDO file scope.
    Main: Start
    X: 2 created
    Test: Start
    X: 3 created    // SSDO created on first use (Notice not destroyed)
    Test: Finished
    Test: Start     // Notice not created here.
    Test: Finished
    X: 4 created
    Main: Finished
    X: 4 destroyed
    X: 2 destroyed  // Main now really finished. after destroying local variables.
    X: 3 destroyed  // Destroy SSDO in reverse order of creation. (3 - 1)
    X: 1 destroyed