How to access global variable ,when we have a local variable with the same name as global variable in C++ ?


When we have a local variable with the same name as global variable, in that case when try to access the global variable it always represents local variable.


For example :

#include<iostream.h>
int var=10; //global variable

void main()
{
int var =5; //local variable
cout<<“var is “<<var; // always print 5
}


So, if we want to access the global variable instead of local one ,we use scope resolution operator(::) with the variable name.
e.g.

#include<iostream.h>
int var=10; //global variable

void main()
{
int var =5; //local variable
cout<<“var is “<< ::var ; // print 10 (value of global variable)
cout<<“var is “<<var ; // print 5 (value of local variable)
}

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *