Storage Classes in C
Storage Classes in C
• These features basically include the scope, visibility, and lifetime which help us to trace the
1. auto
2. extern
3. static
4. register
Syntax
To specify the storage class for a variable, the following syntax is to be followed:
• Auto variables can be only accessed within the block/function they have been declared and not
outside them (which defines their scope). Of course, these can be accessed within nested blocks
within the parent block/function in which the auto variable was declared.
• However, they can be accessed outside their scope as well using the concept of pointers given here
by pointing to the very exact memory location where the variables reside. They are assigned a
int main()
int num1 = 3;
int num2 = 4;
return 0;
}
3. static
• This storage class is used to declare static variables which are popularly used while
writing programs in C language. Static variables have the property of preserving their
value even after they are out of their scope! Hence, static variables preserve the value
of their last use in their scope. So we can say that they are initialized only once and
exist till the termination of the program. Thus, no new memory is allocated because
they are not re-declared.
• Their scope is local to the function to which they were defined. Global static
variables can be accessed anywhere in the program. By default, they are assigned the
value 0 by the compiler.
#include <stdio.h>
void subfun();
int main()
{
subfun(); output
subfun(); st = 1
st = 2
subfun(); st = 3
return 0;
}
void subfun()
{
static int st = 1; //static variable declaration
printf("\nst = %d ", st);
st++;
}
4. register
• This storage class declares register variables that have the same functionality as that of the
auto variables. The only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available.
• This makes the use of register variables to be much faster than that of the variables stored
in the memory during the runtime of the program.
• If a free registration is not available, these are then stored in the memory only. Usually, a
few variables which are to be accessed very frequently in a program are declared with the
register keyword which improves the running time of the program.
• An important and interesting point to be noted here is that we cannot obtain the address of a
register variable using pointers.
#include <stdio.h>
int main()
{
int m1 = 5;
register int m2 = 10;
printf("The value of m1 : %d ",m1);
printf("\nThe value of m2 : %d ",m2);
return 0;
}
output
The value of m1 : 5
The value of m2 : 10