Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static int in function

I came across this code:

void function(int nextFoo)
{
    static int lastFoo = nextFoo; 
    if (nextFoo != lastFoo) 
    {
         // is this possible?
    }
    lastFoo = nextFoo;
}

The coder thinks that lastFoo is only set in the first run, and the last line, is he right? I think (but don't know) that the code in the if block is never run, but can't find verification of that.

like image 361
Dale Avatar asked May 02 '13 19:05

Dale


1 Answers

The coder thinks that nextFoo is only set in the first run, and the last line, is he right?

Yes. static local variables are initialized only once (and not every time the function is entered). In C++11, this is also guaranteed to happen in a thread-safe manner. Per paragraph 6.7/4 of the C++11 Standard:

[...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization [...]

Notice, that if the initialization of the static object throws an exception, its initialization will be re-attempted the next time function() is entered (not relevant in this case, since the initialization of an int cannot throw). From the same paragraph quoted above:

[...] If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. [...]

like image 188
Andy Prowl Avatar answered Sep 23 '22 03:09

Andy Prowl