#include <stdio.h> void func() { static int count = 0; count++; printf("%d ", count); } int main() { for(int i = 0; i < 3; i++) { func(); } return 0; }
The static keyword makes the variable count keep its value between calls to func(). So each time func() is called, count increases by 1, printing 1, then 2, then 3.
Storage classes in C control the scope (where a variable can be accessed), lifetime (how long it exists), and visibility (which parts of the program can see it) of variables and functions.
#include <stdio.h> int main() { extern int x; printf("%d", x); return 0; }
The variable x is declared as extern but never defined anywhere. This causes a linker error because the linker cannot find the actual variable.
The correct syntax is register int count = 10;. The storage class register must come before the type.
#include <stdio.h> void test() { auto int a = 5; static int b = 5; a++; b++; printf("%d %d\n", a, b); } int main() { test(); test(); return 0; }
The auto variable a is reinitialized to 5 each call, then incremented to 6. The static variable b keeps its value between calls, so it increments from 5 to 6 on first call, then from 6 to 7 on second call.