Storage Class in C
Storage Class in C
Topics
• Automatic variables
• External variables
• Static variables
• Register variables
• Scopes and longevity of above types of
variables.
1
BESU, SUMMER-07
Few terms
2
BESU, SUMMER-07
Automatic variables
• Are declare inside a function in which they are to be
utilized.
• Are declared using a keyword auto.
eg. auto int number;
• Are created when the function is called and destroyed
automatically when the function is exited.
3
BESU, SUMMER-07
Example program
int main()
{ int m=1000;
function2();
printf(“%d\n”,m);
}
function1()
{
int m = 10;
printf(“%d\n”,m);
}
function2()
{ int m = 100; Output
function1(); 10
printf(“%d\n”,m); 100
}
1000
4
BESU, SUMMER-07
Few observation about auto variables
• These variables are active and alive throughout the entire program.
• In case local variable and global variable have the same name, the
local variable will have precedence over the global one.
• Sometimes the keyword extern used to declare these variable.
• It is visible only from the point of declaration to the end of the program.
6
BESU, SUMMER-07
External variable (examples)
int main()
{ • As far as main is concerned, y is not
defined. So compiler will issue an error
y=5; message.
. . . • There are two way out at this point
. . . 1. Define y before main.
} 2. Declare y with the storage class extern
int y; in main before using it.
func1()
{
y=y+1
}
9
BESU, SUMMER-07
External declaration (examples)
int main()
{
extern int y;
. . .
. . . Note that extern declaration
} does not allocate storage
func1() space for variables
{
extern int y;
. . .
. . .
}
int y;
10
BESU, SUMMER-07
Multifile Programs and extern variables
file1.c file2.c
file1.c file2.c
13
BESU, SUMMER-07
Internal static variable
14
BESU, SUMMER-07
Examples (internal static)
int main()
{
int I;
for(i =1; i<=3; i++)
stat();
}
void stat()
Output
{
static int x=0; x=1
x = x+1;
x=2
printf(“x = %d\n”,x);
} x=3
15
BESU, SUMMER-07
External static variables
16
BESU, SUMMER-07
Static function
17
BESU, SUMMER-07
Register Variable
18
BESU, SUMMER-07