Program 44) Write a multifunction to illustrate how automatic variables work.
A program with two subprograms function1 and function2 is shown below. m is an automatic variable and it is declared at the beginning of each function. m is initialized to 10, 100, and 1000 in function1, function2, and main respectively.
When executed, main calls function2 which in turn calls function1. When main is active, m = 1000; but when function2 is called, the main's m is temporarily put on t he shelf and the new local m = 100 becomes active. Similarly, when function1 is called, both the previous values of m are put on the shelf and t he latest value of m (=10) becomes active. As soon as function1 (m=10) is finished, function2 (m=100) takes over again. As soon it is done, main (m=1000) takes over. The output clearly shows that the value assigned to m in one function does not affect its value in the other functions; and the local value of m is destroyed when it leaves a function.
PROGRAM
void function1 (void) ;
void function2 (void) ;
main ( )
{
int m = 1000 ;
function2 ( ) ;
printf ("%d\n",m) ; /* Third output */
}
void function1 (void)
{
int m = 10 ;
printf ("%d\n",m) ; /* First output */
}
void function2 (void)
{
int m = 100 ;
function1 ( ) ;
printf ("%d\n",m) ; /* Second output */
}
Output: 10
100
1000
There are two consequences of the scope and longevity of auto variables worth remembering. First, any variable local to main will be normally alive throughout the whole program, although it is active only in main. Secondly, during recursion, the nested variables are unique auto variables, a situation similar to function-nested auto variables with identical names.
No comments:
Post a Comment