Storage Class Specifiers in C Language


  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 Language:

There are 4 storage class specifiers available in C language. They are,
    1. auto
    2. extern
    3. static
    4. register
S.No.
Storage Specifier
Storage place
Initial / default value
Scope
Life
1
auto
CPU Memory
Garbage value
local
Within the function only.
2
extern
CPU memory
Zero
Global
Till the end of the main program. Variable definition might be anywhere in the C program
3
static
CPU memory
Zero
local
Retains the value of the variable between different function calls.
4
register
Register memory
Garbage value
local
Within the function

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.

Example program for auto variable in C Language:

      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

Example program for static variable in C language:

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

Output:

0 1 2 3

Example program for extern variable in C language:

     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

Example program for register variable in C Language:

    • 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


www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

No comments: