blogger Indonesia

Follow judhyns blog

THE CONCEPT OF GLOBAL VARIABLES

Introduction
The various modules can share information by using global variables.

Program
#include
int i =0; //Global variable
main()
{
int j; // local variable in main
void f1(void) ;
i =0;
printf("value of i in main %d\n",i);
f1();
printf("value of i after call%d\n",i);
}
void f1(void)
{
int k; // local variable for f1.
i = 50;
}

Explanation
When you define a variable inside the function block it is called a local variable.

The local variable can be accessed only in the block in which it is declared.

j is the local variable for main and it can be accessed only in the block main. That means you cannot access it in function f1.

k is the local variable for function f1 and it cannot be accessed in main.

The variable i, which is outside main, is called a global variable. It can be accessed from function main as well as function f1.

Any expression in this function is going to operate on the same i.

When you call function f1, which sets the value of i to 50, it is also reflected in main because main and f1 are referring to the same variable, i.

Points to Remember
Global variables can be accessed in all the functions in that file.

Any update to the global variable also affects the other functions, because all functions refer to the same value of i.

When you want to share information between multiple functions, you can use the concept of global variables.

No comments:

feed

PR Check

activesearchresults

judhyn's blog

 

http://www.judhyn.blogspot.com | |