Professional Documents
Culture Documents
Topics
Automatic variables
External variables
Static variables
Register variables
Scopes and longevity of above types of variables.
Few terms
2
These variables are active and alive throughout the entire program.
Unlike local variables they are accessed by any function in the program.
In case local variable and global variable have the same name, the local
variable will have precedence over the global one.
It is visible only from the point of declaration to the end of the program.
External variable (examples)
7
int number; int count;
float length=7.5; main()
main() {count=10;
{ . . . . . .
. . . . . .
} }
funtion1() funtion()
{. . . {int count=0;
. . . . . .
} . . .
funtion1() count=count+1;
{. . . }
. . .
} When the function references the
variable count, it will be referencing
The variable number and length only its local variable, not the global
are available for use in all three one.
function
Global variable example
int x; 8
int fun3()
int main() {
{ x=x+10;
x=10; return(x);
printf(x=%d\n,x); }
printf(x=%d\n,fun1());
printf(x=%d\n,fun2());
printf(x=%d\n,fun3());
} Once a variable has been declared
int fun1() global any function can use it and
{ x=x+10; change its value. The subsequent
return(x); functions can then reference only that
} new value.
int fun2()
{ int x Output
x=1;
return(x); x=10
} x=20
x=1
x=30
External declaration
9
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
}
External declaration(examples)
10
int main()
{
extern int y;
. . .
. . . Note that extern declaration
}
does not allocate storage
func1()
space for variables
{
extern int y;
. . .
. . .
}
int y;
Multifile Programs and extern variables
file1.c 11 file2.c
Internal static variable can be used to count the number of calls made
to function. eg.
int main()
{
int I;
for(i =1; i<=3; i++)
stat();
}
void stat() Output
{ x=1
static int x=0;
x = x+1; x=2
printf(x = %d\n,x); x=3
}
External static variables
16
Keywords : Auto
Storage : Memory
Keywords : Register
Keywords : Static
Storage : Memory
Keywords : Extern
Storage : Memory
Scope : Global