Answer: The four storage classes in C are automatic, register, static and external (global).
A storage class tells four things about a variable: where it is stored, its default initial value, its scope (where it can be used) and its lifetime (how long it exists). C has four storage classes.
| Storage class | Keyword | Stored in | Default value | Scope | Lifetime |
|---|---|---|---|---|---|
| Automatic | auto | Memory (stack) | Garbage | Local to the block/function | Till control stays in that block |
| Register | register | CPU register (if the compiler allows), else memory | Garbage | Local to the block/function | Till control stays in that block |
| Static | static | Memory | Zero | Local to the block/function | Whole program (value kept between calls) |
| External (global) | extern | Memory | Zero | Global (all functions, other files with extern) | Whole program |
1. Automatic: the default class for local variables. A new copy is created each time the block is entered and destroyed on exit. Example: int i; or auto int i;
2. Register: a request to keep the variable in a CPU register for faster access, useful for loop counters. Example: register int i; It is only a hint: the compiler may ignore it and keep the variable in memory. The C language does not fix a limit on the number of register variables or their type; the actual limit depends on the machine. The address operator & cannot be applied to a register variable.
3. Static: example static int count; It is initialised only once (to 0 if no value is given) and keeps its value between function calls, though it is visible only inside its function.
4. External (global): declared outside all functions, e.g. int count; at the top of the file. Any function can use it; another file can use it by declaring extern int count; The extern declaration does not create new storage, it only refers to the existing variable.
Example program:
#include <stdio.h>
int count; /* external (global) variable: default value 0 */
void demo()
{
auto int a = 0; /* automatic: created afresh on every call */
static int s = 0; /* static: initialised once, keeps its value */
register int r; /* register: request to keep it in a CPU register */
for (r = 0; r < 1; r++)
{
a++;
s++;
count++;
}
printf("auto a = %d, static s = %d, extern count = %d\n", a, s, count);
}
int main()
{
demo();
demo();
demo();
return 0;
}Output (actual run):
auto a = 1, static s = 1, extern count = 1
auto a = 1, static s = 2, extern count = 2
auto a = 1, static s = 3, extern count = 3The auto variable a starts from 0 on every call, so it is always 1. The static variable s and the global count keep their values, so they increase 1, 2, 3.