C Language | Structure Declarations | Static Variables - static
Ordinary local variables lose their values when a function finishes. A static variable declared with static has a permanent lifetime. It is visible only inside its function but retains its value until the application exits, like a global variable.
Persistent Local Variables
Variables declared inside a function normally have local lifetimes. They are initialized when the function runs and released when the function returns. This is suitable for temporary storage used during calculations.
Sometimes a program needs longer-lived state. For example, how can a function track how many times it has been called? Incrementing a dedicated counter inside the function is reliable, but an automatic variable loses its value whenever the function returns.
A global counter would retain its value, but another function could accidentally change it. A static variable solves this problem. It retains its value until the program exits but remains inaccessible to other functions.
static Specifier
static type variableName ...
A variable declared this way has a global lifetime. If declared inside a function, it is not destroyed when the function returns.
Code 1
#include <stdio.h>
void ShowCount(void) {
static int iCount = 0;
printf("iCount = %d\n" , iCount++);
}
int main() {
ShowCount();
ShowCount();
ShowCount();
return 0;
}
The ShowCount() function displays how many times it has been called. The static variable iCount is initialized only once and increments across calls.
Static variables can also reduce initialization overhead for values that remain constant, such as character arrays containing fixed strings.