The static variables are used within function/ file as local static variables. They can also be used as a global variable
- Static local variable is a local variable that retains and stores its value between function calls or block and remains visible only to the function or block in which it is defined.
- Static global variables are global variables visible only to the file in which it is declared.
Example: static int count = 10;
Keep in mind that static variable has a default initial value zero and is initialized only once in its lifetime.
#include <stdio.h> /* function declaration */ void next(void); static int counter = 7; /* global variable */ main() { while(counter<10) { next(); counter++; } return 0;} void next( void ) { /* function definition */ static int iteration = 13; /* local static variable */ iteration ++; printf("iteration=%d and counter= %d\n", iteration, counter);}
Result:
iteration=14 and counter= 7 iteration=15 and counter= 8 iteration=16 and counter= 9
Global variables are accessible throughout the file whereas static variables are accessible only to the particular part of a code.
The lifespan of a static variable is in the entire program code. A variable which is declared or initialized using static keyword always contains zero as a default value.