Write a multifunction program to illustrate the properties of global variables.
A program to illustrates the properties of global variables is presented. Note that variables x is used in all functions but none except fun2, has a definition for x. Because x has been declared 'above' all the functions, it is available to each function without having to pass x as a function argument. Further, since the value of x is directly available, we need not use return(x) statements in fun1 and fun3. However, since fun2 has a definition of x, it returns its local value of x and therefore uses a return statement. In fun2, the global x is not visible. The local x hides its visibility here.
#include <stdio.h>
int fun1(void);
int fun2(void);
int fun3(void);
int x ; /* global */
void main( )
{
x = 10 ; /* global x */
printf("x = %d\n", x);
printf("x = %d\n", fun1());
printf("x = %d\n", fun2());
printf("x = %d\n", fun3());
getch();
}
fun1(void)
{
return(x = x + 10);
}
int fun2(void)
{
int x ; /* local */
x = 1 ;
return (x);
}
fun3(void)
{
return(x = x + 10); /* global x */
}
OUTPUT
x = 10
x = 20
x = 1
x = 30
A program to illustrates the properties of global variables is presented. Note that variables x is used in all functions but none except fun2, has a definition for x. Because x has been declared 'above' all the functions, it is available to each function without having to pass x as a function argument. Further, since the value of x is directly available, we need not use return(x) statements in fun1 and fun3. However, since fun2 has a definition of x, it returns its local value of x and therefore uses a return statement. In fun2, the global x is not visible. The local x hides its visibility here.
#include <stdio.h>
int fun1(void);
int fun2(void);
int fun3(void);
int x ; /* global */
void main( )
{
x = 10 ; /* global x */
printf("x = %d\n", x);
printf("x = %d\n", fun1());
printf("x = %d\n", fun2());
printf("x = %d\n", fun3());
getch();
}
fun1(void)
{
return(x = x + 10);
}
int fun2(void)
{
int x ; /* local */
x = 1 ;
return (x);
}
fun3(void)
{
return(x = x + 10); /* global x */
}
OUTPUT
x = 10
x = 20
x = 1
x = 30
No comments:
Post a Comment