In C language, storage classes specify how and where a variable is stored in memory. There are four storage classes in C:
- Automatic: This is the default storage class for all local variables. Variables with automatic storage are created when the function is called and destroyed when the function returns. They are stored on the stack and have undefined values until initialized.
- Register: Variables declared with the register storage class are stored in CPU registers instead of memory. This can improve performance for frequently used variables. However, the compiler may ignore the request to use a register and store the variable in memory.
- Static: Variables declared with the static storage class are stored in memory and retain their values between function calls. Static variables are initialized to 0 by default, but you can also provide an explicit initialization value.
- Extern: Variables declared with the extern storage class are not actually defined in the current file, but are assumed to be defined in another file. The extern keyword is used to declare a global variable that is defined in another file.
Here is an example of how to use storage classes in C:
// Automatic variable
int a = 5;
// Register variable
register int b = 10;
// Static variable
static int c = 15;
// Output variable values
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("c = %d\n", c);
// Modify variable values
a = 6;
b = 11;
c = 16;
In this example, the function
my_function contains three variables with different storage classes. The variable
a has automatic storage,
b has register storage, and
c has static storage. The function outputs the initial values of these variables, modifies their values, and then returns. When the function is called again, the values of
b are re-initialized to their default values, but the value of
c is retained between function calls because it has static storage. Finally, the program calls
my_function three times from
main to demonstrate the effect of the different storage classes.