Storage Class In C
A storage class defines the scope (visibility)
and life-time of variables and/or functions within a C Program. They precede
the type that they modify. We have four different storage classes in a C
program −
- auto
- register
- static
- extern
Fig: Storage class in c |
The auto Storage Class
The auto storage class is the
default storage class for all local variables.
Example:
{
int mount;
auto int mount;
}
Program
#include<stdio.h>
Int main()
{
auto int j=1;
{
auto int j=2;
{
auto int j=3;
printf(“%d”,j);
}
printf(“ \t %d”,j);
return 0;
}
Output:
3 2 1
The register Storage Class
The register storage
class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the
register size (usually one word) and can't have the unary '&' operator
applied to it (as it does not have a memory location).
Example:
{
register int
arr;
}
It should also be noted that defining 'register' does not mean that the
variable will be stored in a register.
Program
#include<stdio.h>
main()
{
{ register int weight;
int *ptr=&weight;
}
}
Output:
Error:address
of register variable ‘weight’ requested
The static Storage Class
The static storage
class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope.
It causes that variable's scope to be
restricted to the file in which it is declared.
when static is
used on a global variable, it causes only one copy of that member to be shared
by all the objects of its class.
Example:
static int
mount=10;
Program
#inlcude<stdio.h>
void
next(void);
static
int counter=7;
main()
{
While(counter<10)
next();
counter++;
return
0;
void
next(void)
{
static
int mount=13;
mount++;
printf(“mount=%d
and counter=%d\n”,mount,counter);
}
Output:
Mount=14
and counter=7
Mount=15
and counter=8
Mount=16
and counter=9
The extern Storage Class
The extern storage
class is used to give a reference of a global variable that is visible to ALL
the program files. When you use 'extern', the variable cannot be initialized
however, it points the variable name at a storage location that has been previously
defined.
The extern
modifier is most commonly used when there are two or more files sharing the
same global variables or functions.
Example:
extern
void display();
program
First file : main.c
#include<stdio.h>
extern i;
main()
{
printf(“value
of the external integer is= %d\n”,i);
return 0;
}
Second file:support.c
#include<stdio.h>
i=48;
Output:
Value of the external
integer is =48
No comments:
Post a Comment