x

C – Storage Class Specifiers

Prev     Next

Storage class specifiers in C language tells the compiler where to store a variable, how to store the variable, what is the initial value of the variable and life time of the variable.


Syntax:

storage_specifier data_type variable _name;

Types of Storage Class Specifiers in C:

There are 4 storage class specifiers available in C language. They are,

  1. auto
  2. extern
  3. static
  4. register
Storage Specifier 
Description
auto Storage place: CPU Memory
Initial/default value: Garbage value
Scope: local
Life: Within the function only.
extern Storage place: CPU memory
Initial/default value: Zero
Scope: Global
Life: Till the end of the main program. Variable definition might be anywhere in the C program.
static
Storage place: CPU memory
Initial/default value: Zero
Scope: local
Life: Retains the value of the variable between different function calls.
register
Storage place: Register memory
Initial/default value: Garbage value
Scope: local
Life: Within the function only.

Note:

  • For faster access of a variable, it is better to go for register specifiers rather than auto specifiers.
  • Because, register variables are stored in register memory whereas auto variables are stored in main CPU memory.
  • Only few variables can be stored in register memory. So, we can use variables as register that are used very often in a C program.

1. Example program for auto variable in C:

The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto variables by default.


Output:

0 0 0 0

2. Example program for static variable in C:

Static variables retain the value of the variable between different function calls.

Output:

0 1 2 3

3. Example program for extern variable in C:

The scope of this extern variable is throughout the main program. It is equivalent to global variable. Definition for extern variable might be anywhere in the C program.

Output:

The value of x is 10
The value of y is 50

4. Example program for register variable in C:

  • Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory.
  • Register variables will be accessed very faster than the normal variables since they are stored in register memory rather than main memory.
  • But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits)

Output:

value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

Prev     Next



Like it? Please Spread the word!