Storage classes in C determine the lifetime, scope, and storage location of variables. They control how variables are allocated, initialized, and accessed during program execution. C provides four storage classes: automatic, register, static, and extern. Each storage class has its own characteristics and usage scenarios.
The automatic storage class is the default storage class for local variables declared within functions or blocks. Variables with automatic storage are created when the function or block is entered and destroyed when it is exited. They are typically used for temporary or short-lived variables.
#include<stdio.h> int main() { int integer; auto char character; float decimal; printf("%d %c %f",integer,character,decimal); }
5 Garbage Garbage Garbage Here 'auto' keyword not not use for i and f, by default they belong to auto storage class. Then all the variable get default Garbage value.
The register storage class is used to declare local variables that should be stored in the CPU registers instead of memory. It provides faster access to variables. However, the compiler may choose to ignore the register keyword and store the variable in memory.
#include<stdio.h> int main() { register int a=10; int *p; p=&a; printf("%u",p); }
Compilation error Here we are trying to reference a register a register variable which gives a compilation error.
The static storage class is used to declare variables that retain their values between function calls. Static variables are initialized only once and persist throughout the program's execution. They have a longer lifespan than automatic variables and are commonly used for maintaining state or sharing data across function calls.
#include<stdio.h> void staticexample() { static int x; { static int x=5; printf("%d",x); x++; } printf("%d\n",x); x++; } int main() { staticexample(); staticexample(); }
5 0 6 1
The extern storage class is used to declare variables that are defined in another file. It allows variables to be accessed across multiple source files by using the extern keyword. The actual definition of an extern variable must be provided in another file.
When extern specifier is used with a variable declaration then no storage is allocated to that variable and it is assumed that the variable has already been defined elsewhere in the program. When we use extern specifier the variable cannot be initialized because with extern specifier variable is declared, not defined.
#include<stdio.h> extern int i; int main() { printf("i=%d\n",i); } int i=10;
i=10 if you change the statement extern int x; to extern int x = 50;
you will again get an error "Redefinition of 'x'" because with extern specifier the variable cannot be initialized,
if it is defined elsewhere. If not then extern declaration becomes a definition.