Monday, February 20, 2012

Static variable in C!!

In C programming language there are four storage classes namely auto, static, extern and register used for storage location for the variables and scope of the variable. lets see about the static storage class here. To declare the variable to be static , need to use static keyword. this static uses two ways in C.

1.Limiting the scope of the variable to file: Generally for global variables, the scope of the variable is across the application. if you want to limit the scope of the variable to file itself, make the global variable as static.

int g=10; // global value can access anywhere in the application/program
static int s=20; //global and specific to this file. cant  access outside the file
int test()
{
int a; // local to test() function
}

main()
{
int l=30; //local variable cant access outside the main
}

2.Fixed duration: By default all local variable scope will be limited to the function or block only. the data will not be available after reaching out of the block/function. if you want to restore the data use static.
int test()
{
int a=10; // local to test() function
printf("a value is %d\n",a);
a++;
}
int static_test()
{
static  int st=10; // static variable, value will be restored
printf("st value is %d\n",st);
st++;
}
main()
{
printf("** non-static value **\n");
test();
test();
test();
printf("** static value **\n");
static_test();
static_test();
static_test();


Output:
** non-static value **
a value is 10
a value is 10
a value is 10
** static value **
st value is 10
st value is 11
st value is 12

Note: If not initialized, default value set to zero for all static and global variables.

No comments:

Popular Posts