Program 46) Write a program to illustrate the properties of static variable.
This program explains the behaviour of a static variable
PROGRAM
void stat (void) ;
main ( )
{
int i ;
for (i = 1; i <=3; i++)
stat ( ) ;
}
void stat (void)
{
static int x = 0 ;
x = x + 1 ;
printf ("x = %d\n", x) ;
}
Output: x = 1
x = 2
x = 3
A static variable is initialized only once, when the program is compiled. It is never initialized again. During the first call to stat, x is incremented to 1. Because x is static, this value persists and therefore, the next call adds another 1 to x giving it a value of 2. The value of x becomes three when the third call is made.
Had we declared x as an auto variable, the output would have been:
x = 1
x = 1
x = 1
This is because each time stat is called, the auto variable x is initialized to zero. When the function terminates, ita value of 1 is lost.
An external static variable is declared outside of all functions and is available to all the functions in that program. The difference between a static external variable and a simple external variable is that the static external variable is available only within the file where it is defined while the simple external variable can be accessed by other files.
It is also possible to control the scope of the function. For example, we would like a particular function accessible only to the functions in the file in which it is defined, and not to any function in other files. This can be accomplished by defining 'that' function with the storage class static.
No comments:
Post a Comment