In C, a Storage Class defines the scope (visibility) and lifetime (how long it stays in memory) of variables and/or functions.
There are four main storage classes in C:
autoexternstaticregisterauto Storage Classauto is the default storage class for all local variables defined within a function or block. They are created when the block is entered and destroyed when the block is exited.
void myFunction() {
int x = 10; // This is an auto variable by default
auto int y = 20; // Explicitly defining it as auto (rarely done)
}
static Storage ClassThe static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope.
This makes static variables excellent for maintaining state across function calls!
#include <stdio.h>void counterFunction() { static int count = 0; // Initialized only once count++; printf("Count is %d\n", count); }
int main() { counterFunction(); // Count is 1 counterFunction(); // Count is 2 counterFunction(); // Count is 3 return 0; }
extern Storage ClassThe extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use extern, the variable cannot be initialized; it just points the variable name at a storage location that has been previously defined in another file.
Which storage class preserves the value of a local variable between function calls?