Storage Class
Storage Class
Along with the life time of a variable, storage class also determines
variable's storage location (memory or registers), the scope (visibility
level) of the variable, and the initial value of the variable.
Storage Class Types
Storage Class Types
Automatic Storage Class
A variable defined within a function or block
with auto specifier belongs to automatic
storage class.
Variables belonging to register storage class are local to the block which they are
defined in, and get destroyed on exit from the block.
Only a few variables are actually placed into registers, and only certain types are
eligible; the restrictions are implementation-dependent.
int main()
{
int num1,num2;
register int sum;
return(0);
}
Static Storage Class
The static specifier gives the declared variable static storage
class.
The static specifier has different effects upon local and global
variables.
Static Storage Class - Example
#include <stdio.h>
void staticDemo() int main()
{ {
int a=1; staticDemo();
staticDemo();
{ }
static int i = 1;
printf("%d ", i);
i++;
}
printf("%d\n",a);
a++;
}
External Storage Class
The extern specifier gives the declared variable external storage class.
The principal use of extern is to specify that a variable is declared with external
linkage elsewhere in the program.
A definition causes storage to be allocated for the variable or the body of the
function to be defined.
The same variable or function may have many declarations, but there can be only
one definition for that variable or function.
When we use extern specifier the variable cannot be initialized because with
extern specifier variable is declared, not defined.
Extern Variable
Extern Variable - Example
Problem when extern is not used
int main()
{
a = 10; //Error: cannot find definition of variable 'a'
printf("%d", a);
}
#include <stdio.h>
extern int x;
int main()
{
printf("x: %d\n", x);
}
int x = 10;
Extern Variable - example
File1.c
#include <stdio.h>
int i=10;
void fun()
{
i++;
printf("%d",i);
}
File2.c
# include"file1.c";
main()
{
extern int i;
fun();
}
Output: 11
Extern Variable
• Example 4:
#include "somefile.h"
extern int var;
int main(void)
{
var = 10;
return 0;
} - Supposing that somefile.h has the definition of var. This program will be compiled successfully.
• Example 5:
extern int var = 0;
int main(void)
{
var = 10;
return 0;
} - If a variable is only declared and an initializer is also provided with that declaration, then the
memory for that variable will be allocated i.e. that variable will be considered as defined.
Therefore, as per the C standard, this program will compile successfully and work.