C++ – Benefits of Defining Constant Local Variables as Static

cc++11c++14

void Animation::playAnimation() const
{
    static const int index = 0;
    const std::string& animationFileName = 
    m_animationContainer.getAnimationName(index);
    static const int zOrder = -1;
    static bool isLooping = false;

    AnimationBank::play(animationFileName,
                        zOrder,
                        isLooping);
}

Is there any benefit to to define constant local variables as static? Or it is unnecessary and even bad practice.

Best Answer

Beyond @Christophe's very good answer, the code generated for the static is most likely worse than the one for the local variable, so if you're interested the under-the-hood benefit, statics are worse on modern processors.

The reason is that the statics must be located somewhere in memory that can be found by all the other threads and by all the other invocations. This basically means putting them in global memory.

Over the years, processors & compilers together have significantly optimized access to local variables due to the popularity of their usage, as compared with other variables, such as globals, statics, and fields. The compiler may choose to store a local variable in a CPU register, and even if it doesn't (so it uses the invocation stack instead) all of the stack is almost certainly in the cache. Accessing the stack is usually a short displacement addressing mode (off the stack pointer register). However, accessing globals or statics usually requires and extended offset or absolute address, so the resulting instructions doing so are longer than their equivalent for stack memory access.

All that being said, due to the combination of static and const the compiler may detect that it can substitute the constant value at the point of usage, so perhaps use of const mitigates the above. Still, your snippet shows at least one non-const statics, so perhaps the discussion is topical.