1️⃣ What is a Static Variable?
A static variable:
- Remains in memory while the program is running
- Retains its value between function calls
- Is initialized only once
2️⃣ Example: Static Variable Inside a Function
#include <stdio.h>
void test() {
static int x;
x++;
printf("%d\\n", x);
}
int main() {
test();
test();
test();
}
Output:
1
2
3
🔎 Why is the Output 1 2 3?
Step-by-step understanding:
static int x; is created only once.
- Since it is static and not initialized, it becomes 0 by default.
- First call → x = 0 → x++ → prints 1
- Second call → x is still 1 → x++ → prints 2
- Third call → x is 2 → x++ → prints 3
The key idea:
Static variable keeps its value even after the function ends.