Program 45) Write a multifunction program to illustrate the properties of global variables.
This program illustrate the properties of global variables. Note that variable 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.
PROGRAM
int fun1 (void) ;
int fun2 (void) ;
int fun3 (void) ;
int x ; /* Global */
main ( )
{
x = 10 ; /* Global */
printf ("x = %d\n", x) ;
printf ("x = %d\n", fun1() ) ;
printf ("x = %d\n", fun2() ) ;
printf ("x = %d\n", fun3() ) ;
}
fun1 (void)
{
x = x + 10 ;
}
int fun2 (void)
{
int x ; /* Loacl */
x = 1 ;
return (x) ;
}
fun3 (void)
{
x = x + 10 ; /* Global */
}
Output: X = 10
X = 20
X = 1
X = 30
Once a variable has been declared as global, any function can use it and change its value. Then, subsequent functions can reference only that new value.
No comments:
Post a Comment