A global variable is one whose value can be used anywhere in the program. Its value can be used in the Main() function and all other functions in the program. However, a local variable is one whose value is local to the function i.e. its value can be used in that particular function only where it is declared. A global variable is defined before the Main() function. Same name can be given to local and global variables. For example in the following program segment
#include<iostream.h>; int s1 = 5; // global variable void f1() { int s1 = 15; // local variable } void main() { int s1 = 10; // local variable }
Here s1 declared before the main() function is a global variable whereas s1 declared in the main() function and the function f1() are local variables. In the main() function, the value of s1 will be 10 and in the function f1(), the value of s1 will be 15. In case it is desired to use the value of the global variable, scope resolution operator(::) has to be used before the variable.
Example
Illustrates the use of scope resolution operator to use the value of global variable.
#include int val = 250; void main() { int val = 300; // displaying global variable cout<< :: val <<"\n"; // displaying local variable cout << val; }