c - confusion about static variables -


i have confusion in concepts of static integer.when initialize static integer in main function i.e

static int i; 

now static integer assigned value 0.now in next step:

i++; 

i becomes 1.

now program terminates. want know program produce on its' next run. also, happen if entire program closed? understand first line static int i; next value when function next run should retain value of when run. if so, advantage of making variable static? variable have time limit or can stored forever? value if ran function again?

in c, "static" means variable has local scope within global storage.

the scope of variables in c block. in other words variables can used inside block declared. , keep values until block ends, being lost after that. example:

{    int a;     // can used here    {       int b;       // , b can used here       {          int c;          // a,b , c can used here       }       //just , b can used here. c not available anymore     }     // can used here. neither b nor c available anymore  } 

this true except global variables can used along program.

the other exception static variable. seen inside block keeps value after block over.

this means if declare static variable inside function, maintain value between function calls.

for example, function below has local variable. local variables have scope of block (this means can access variable 'var' inside block {} declared, in case below inside function):

void countfunction(void) {   int var = 0;   var = var + 1;   printf("value %d\n", var); } 

once variable not static, every time call function print "value 1" because variable stored in stack allocated on function call , deallocated after function returns.

if change var static,

void countfunction(void) {   static int var = 0;   var = var + 1;   printf("value %d\n", var); } 

the first time call function var initialized 0 , function show "value 1". nevertheless, @ second time, var allocated , @ global area. not initialized again , function display "value 2".

this within program execution.

although static variable allocated long program executes, not keep value after program finishes (the program free of memory). way keep value next run store @ non-volatile media disk.

hope helps.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -