Search code examples
c++functionstatic-variables

Call function with local static variable


Assume that we have simplest function with local static variable:

int f()
{
    static int a = 0;
    return ++a;
}

Let's call this function multiple times and print result:

int main()
{
    int a  = f();
    int b  = f();
    std::cout<<a<<b;
}

Output is "12" - ok, as expected. But this call

int main()
{
   std::cout<<f()<<f();
}

produces reverse order - "21". Why?


Solution

  • Because the order in which functions are executed in a compound statement is undefined. This means that by the end of the std::cout<<f()<<f() line, you are guaranteed to have called f() twice, and you are guaranteed to have printed the two results, but which result is first is not defined and can vary across compilers.

    There is a difference because f() has side effects. Side effects are results of the function that can't be measured by its return value. In this case, the side effect is that the static variable is modified. If the function had no side effect (or if you were calling multiple functions with no overlapping side effects), which function is called first wouldn't change anything.