Storage class in c
In c, Storage class specifies variable scope, lifetime, default value and the memory space allocated during execution of the program.
c programming language supports 4 storage class specifiers:
- auto
- extern
- static
- register
auto
auto is default storage class of variables declared or defined inside a function.
These variables are also called as automatic or local variables. They are only accessible inside a function where they are declared.
Default value for variables with auto storage class is Garbage.
Example
void main()
{
// A variable inside a function, by default becomes automatic variable
int a = 20;
// A variable with auto specifier
auto int b = 30;
}
extern
To access a global variable of one c program/source file in other c program/source files, extern storage class is used.
It is used to declare & use a variable in a program which is already defined in some other c program/source file.
Example
// myfile1.c
int count;
void num()
{
count=10;
}
// myfile2.c
// Including myfile1.c
#include"myfile1.c"
void main()
{
// Accessing a global variable defined in myfile1.c
extern int count;
num();
}
static
variable with static specifier created & initialized once in their lifetime & holds the value between function call until the program execution ends.
Default value for variable with static specifier is 0. static specifier can also be used with automatic & extern variables.
Example
#include<stdio.h>
void mycounter();
int main()
{
mycounter();
mycounter();
mycounter();
mycounter();
mycounter();
mycounter();
return 0;
}
void mycounter()
{
static int a = 0 ;
printf( "%d ", a) ;
a = a + 1;
}
register
Variables with register storage class specifier are stored in CPU register for quicker access.
Following are the facts related to the register storage class:
- Variables with register storage class are local to the function where they are declared.
- Compiler may store the variables in memory(RAM), but compiler does not
guarantee it to store in CPU register. - Default value for variables with register storage class is garbage.
Example
int main()
{
register int a;
return 0;
}