What does a static variable mean with example?- C faqs with answers

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 initialised by using keyword static before variable name.

For 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 initialised only once no matter how many times that function in which it resides is called. It may be used as a count variable.

void count(void) {
static int count1 = 0;
int count2 = 0;
printf("\nValue of count1 is %d Value of count2 is %d", count1, count2);

//In Main function:
main() {

Output would be:
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:

Top Blogs