5. Static variables
•Static variables are defined using the keyword static
−These variables are initialized only once
−Therefore, the compiler persists with the variable till the end of the program
Systems Architecture - 4. Modular programming in C 27
#include <stdio.h>
void my_function() {
int regular_int = 0;
static int static_int = 0;
regular_int++;
static_int++;
printf("regular_int = %d, static_int = %d\n", regular_int, static_int);
}
int main() {
for (int i = 0; i < 10; i++) {
my_function();
}
}
regular_int = 1, static_int = 1
regular_int = 1, static_int = 2
regular_int = 1, static_int = 3
regular_int = 1, static_int = 4
regular_int = 1, static_int = 5
regular_int = 1, static_int = 6
regular_int = 1, static_int = 7
regular_int = 1, static_int = 8
regular_int = 1, static_int = 9
regular_int = 1, static_int = 10