c - What happens to initialization of static variable inside a function -


after stumbling onto this question , reading little more here (c++ issue works same in c/c++ afain) saw no mention realy happening inside function.

void f(){   static int c = 0;   printf("%d\n",c++); }  int main(){   int  = 10;   while(i--)     f();   return 0; } 

in snippet, c lifetime entire execution of program, line static int c = 0; has no meaning in next calls f() since c defined (static) variable, , assignment part obsolete (in next calls f()), since takes place @ first time.

so, compiler do? split f 2 functions - f_init, f_the_real_thing f_init initializes , f_the_real_thing prints, , calls 1 time f_init , onward, calls f_the_real_thing?

although standard not dictate how compilers must implement behavior, compilers less sophisticated thing: place c static memory segment, , tell loader place 0 c's address. way f comes straight pre-initialized c, , proceeds printing , incrementing if declaration line not there.

in c++ optionally adds code initialize c static initialization function, initializes static variables. in case, no call required.

in essence, amounts c starting lifetime before first call f. can think of c's behavior if static variable outside f() visibility constrained f()'s scope.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -