In C, a static variable are those variables whose lifetime is till the end of the program. It means that once it is initialized, it will live in the program till it ends. It can retain its value between function calls, unlike regular local variables that are reinitialized each time the function is called.
Syntax of Initialization
Initializing a static variable is as simple as the normal variable but they can only be initialized using constant literals.
static type name = value;
where,
- type: Type of the variable.
- name: Name assigned to the variable.
- value: Value to be assigned.
If no value is provided during initialization, static variables are automatically initialized to zero for basic data types like int, float, etc., and to NULL for pointers.
Example
#include<stdio.h>
int main() {
// Creating and initializing static variable
static int i = 50;
printf("%d", i);
return 0;
}
Output
50
In this program, we assigned the literal '50' to the static integer value i. It works as it follows the rules of the static variable assignment. But if we try to assign it a non-literal value such as below code, it fails in compilation.
#include<stdio.h>
int f(void) {
return 50;
}
int main() {
// Assigning non literal value
static int i = f();
printf("%d", i);
return 0;
}
Output
solution.c: In function ‘main’:
solution.c:10:20: error: initializer element is not constant
10 | static int i = f();
| ^