by Dinesh Thakur Category: Operator

 

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 sl = 5; // global variable

 

void f1()

 

{

 

int sl = 15; // local variable

 

.

 

.

 

}

 

void main()

 

{

 

int sl = 10; // local variable

 

}

 

 

 

Here sl declared before the main() function is a global variable whereas sl 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 s 1 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 <iostream.h>

 

int val = 250;

 

void main()

 

{

 

int val = 300;

 

II displaying global variable

 

cout<< :: val <<"\n";

 

II displaying local variable

 

cout << val;

 

}

 



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.