Storage Classes
*
1
Storage Classes
*
2
Storage Classes
void f_1(int j, int k)
{
int total = 0;
β¦..;
β¦β¦;
}
float f_2(int k)
{
int total = 1;}
*
3
These two total are different
These two k are different
So, it is good to do : when f_1( ) is called total in f_1 can be created and destroyed when f_1( ) is over.
Storage Classes
int total_no_stud;
int main( )
{ β¦;
a = find_average( β¦ );
b = find_max( β¦ );
β¦ ;
}
float find_average( β¦ )
{ β¦;
avg = total/total_no_stud;
β¦;
}
*
4
float find_max( β¦ )
{
β¦;
for(j =0; j< total_no_stud; j++) {
β¦;
}
β¦;
}
total_no_stud should be same in both functions, since it is a global information.
Storage Classes
*
5
Storage Classes
*
6
auto
*
7
auto
int a; /* auto int a; */
a = 50;
{
int a;
a = 100;
printf(β%d\nβ, a);
}
printf(β%d\nβ, a);
a ++;
printf(β%d\nβ, a);
}
*
8
$ ./a.out
100
50
51
$
auto ( Let us remove interior declaration)
int a;
a = 50;
{
int a;
a = 100;
printf(β%d\nβ, a);
}
printf(β%d\nβ, a);
a ++;
printf(β%d\nβ, a);
}
*
9
$ ./a.out
100
100
101
$
Scope means where the identifier can be referenced in a program
int a;
a = 50;
{
int a;
a = 100;
printf(β%d\nβ, a);
}
printf(β%d\nβ, a);
a ++;
printf(β%d\nβ, a);
}
*
10
Scope of this a is the main function
Scope of this a is within the interior braces
Interior a, if declared, hides the exterior a.
In this case, exterior a is invisible from interior block.
Storage duration
*
11
register
*
12
Static storage duration
*
13
Static storage duration
*
14
Global variables
*
15
Global Variables
*
16
Static variables
static int count = 1;
are local to the function in which they are declared but retains its value even after the function is exited.
*
17
static
void f_1(void);
int main( )
{
f_1();
f_1();
f_1();
}
void f_1(void)
{
static int count = 1;
printf(β%d\nβ, count);
count ++;
}
*
18
$./a.out
1
2
3
$
static
void f_1(void);
int main( )
{
f_1();
f_1();
f_1();
}
void f_1(void)
{
static int count;
count = 0;
printf(β%d\nβ, count);
count ++;
}
*
19
$./a.out
0
0
0
$
Static
int fib(int n)
{
static int counter = 0;
counter ++;
printf(βIn fib with counter = %d \nβ, counter);
if (n==0) return 1;
else return n*fib(n-1);
}
*
20
What is the output if we call fib(4) ?
And now ?
extern and static
*
21