Skip to content
thesarfo

Note

C: Storage Classes

What a storage class is, using static to persist a variable's value across calls, and extern for cross-file globals.

views 0
#include <stdio.h>
/* A class of storing variables. It tells the compiler where to store the data. ie-stack or heap. Or if variable data storage is already declared elsewhere */
void print_plus_one(void){
static int a = 0; /* static storage class */
printf("%d\n", a);
a++; /* increment the static value*/
}
int main(void){
print_plus_one(); /* prints "0" */
print_plus_one(); /* prints "1" */
print_plus_one(); /* prints "2" */
print_plus_one(); /* prints "3" */
return 0;
}
/* Note that, normally the variable a will only be local to the print_plus_one function, and be stored on the stack. But using the "static" keyword it tells the compiler to store it on the heap instead. Hence making it behave more like a global variable. */
/* There's another storage class called "extern", which tells the compiler that the definition of the variable is in a different file. This allows you to reference a global variable from a file even if its defined somewhere else. */