Search code examples
c++global-variables

Proper Global Variable definition/declaration


This is probably a pretty straight forward question but for some reason I haven't been able to find an answer on the great interwebs so far.

When using global variables, I know global variables are bad and should for the most part be avoided, but on those rare occasions where a global variable gets the job done best, should the global variable be both declared and initialized at once? I have been recently trying to drill into my head the mantra "always initialize variables upon declaration when possible" since this usually saves many headaches later and is encouraged with C++. Does this rule apply to global variables as well though?

If you initialize a variable in its global scope when declaring it, how does this affect the program? Is this best practice?

You're advice is very much appreciated!


Solution

  • You want to initialize variables at the point they are declared whenever possible, regardless of their scope.

    For global variables, if you don't initialize them when they are declared, you need to initialize them after your program starts running, which leaves open the possibility that the global will be used before this occurs. Classes, with constructors, will be default constructed, which can cause work to be done and thrown out when the variable is assigned its proper value.

    Global variables have another problem: the order they are constructed/initialized is only partially defined by the language. If you have two global variables that are declared in different source modules, you do not know which one will be constructed first. This can lead to the static initialization order fiasco.

    So you can run into problems if you initialize them, or different problems if you don't. This is one reason why global variables should be avoided.

    What is the solution? You can wrap your global variables into an accessor function. This will ensure that the variable has been properly initialized. So rather than the plain declaration:

    SomeType big = ReadBig();
    

    you can place it into a function:

    const SomeType &GetBig() {
        static SomeType big = ReadBig();
        return big;
    }
    

    This also has the advantage of having your global variable const, so that it cannot be changed if this is necessary.