Wednesday, March 24, 2010

Static variable inside a function

int nonestatic_var_Test(void)
{
int number_of_times=0;

for(int y=0; y<10; y++)
{
number_of_times++;
}

return number_of_times;

}


int static_var_Test(void)
{
static int static_number_of_times = 0;

for(int y=0; y<10; y++)
{
static_number_of_times++;
}

return static_number_of_times;

}


int main()
{

int i;
int func_invoke_times;

for(i=0;i<10;i++)
func_invoke_times=static_var_Test();

printf("static_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=static_var_Test();
printf("static_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=nonestatic_var_Test();

printf("nonstatic_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=nonestatic_var_Test();
printf("nonstatic_func_invoke_times is %d\n",func_invoke_times);

}





result:

static_func_invoke_timers is 100
static_func_invoke_timers is 200
nonstatic_func_invoke_timers is 10
nonstatic_func_invoke_timers is 10

No comments: