Static int in function

c++, function, static

Solution

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. [...]

Problem

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.

Original source