Write a multifunction to illustrate how automatic variables work.
A program with two subprograms function1 and function2 is shown 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 the 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 the 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.
#include <stdio.h>
void function1(void);
void function2(void);
void main( )
{
int m = 1000;
function2();
printf("%d\n",m); /* Third output */
getch();
}
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
A program with two subprograms function1 and function2 is shown 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 the 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 the 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.
#include <stdio.h>
void function1(void);
void function2(void);
void main( )
{
int m = 1000;
function2();
printf("%d\n",m); /* Third output */
getch();
}
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
No comments:
Post a Comment