c++ - Static int in function -


i came across code:

void function(int nextfoo) {     static int lastfoo = nextfoo;      if (nextfoo != lastfoo)      {          // possible?     }     lastfoo = nextfoo; } 

the coder thinks lastfoo set in first run, , last line, right? think (but don't know) code in if block never run, can't find verification of that.

the coder thinks nextfoo set in first run, , last line, right?

yes. static local variables initialized once (and not every time function entered). in c++11, guaranteed happen in thread-safe manner. per paragraph 6.7/4 of c++11 standard:

[...] if control enters declaration concurrently while variable being initialized, concurrent execution shall wait completion of initialization [...]

notice, if initialization of static object throws exception, initialization re-attempted next time function() entered (not relevant in case, since initialization of int cannot throw). same paragraph quoted above:

[...] if initialization exits throwing exception, initialization not complete, tried again next time control enters declaration. [...]


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -