Sunday, 12 August 2012

Static variable


A static variable is a special variable that is stored in the data segment unlike the default automatic variable that
is stored in stack. A static variable can be initialized by using keyword static before variable name.
Example:
static int a = 5;
A static variable behaves in a different manner depending upon whether it is a global variable or a local variable.
A static global variable is same as an ordinary global variable except that it cannot be accessed by other files in the same program / project even with the use of keyword extern. A static local variable is different from local variable. It is initialized only once no matter how many times that function in which it resides is called. It may be used as a count variable.
Example:
#include <stdio.h>
//program in file f1.c
void count(void) {
static int count1 = 0;
int count2 = 0;
count1++;
count2++;
printf("\nValue of count1 is %d, Value of count2 is %d", count1, count2);
}/
*Main function*/
int main(){
count();
count();
count();
return 0;
}
Output:
Value of count1 is 1, Value of count2 is 1
Value of count1 is 2, Value of count2 is 1
Value of count1 is 3, Value of count2 is 1

No comments: