Accessing a global variable value when a global and local variable have same names in CPP - UCS - Unleash-Coding-Skills

Tuesday, 5 June 2018

Accessing a global variable value when a global and local variable have same names in CPP - UCS


Accessing a global variable value when a global and local variable has same names in CPP :

You might have come across a scenario in C language when global and local variables have the same name while accessing that variable inside block or function we can only get the local variable value but not the global variable value.


Here Comes the power of CPP or C++:

In CPP we can have a solution for this problem by using a scope resolution operator.
Thinking ............ Thinking ..............  Thinking ......................

You don't need to worry the scope resolution operator is represented by "::"


By printing the variable or accessing or using a variable in our code we can use by

 "::variable-name"

You can understand it better by this example:

#include <iostream>
using namespace std;
int x=20;
int main()
{
int x=10;
{
int x=30;
cout<<"inner block value and global value:"<<x<<" "<<::x<<endl;
int u = ::x;
cout<<u<<endl;
}
cout<<"outer block value and global value:"<<x<<" "<<::x<<endl;
return 0;
}

Output:

inner block value and global value: 30 20
20
outer block value and global value:10 20

Here in this example, we can see the inner block has the "x" variable value is "30" so we can use it normally but in order to use the global value we use "::x" for assigning to another variable and for printing also so the output we got is:
 inner block value and global value: 30 20
20
Similarly, for the other block for "x", the output is 10 and for "::x" the output is a global value which is 10 20.
outer block value and global value:10 20

Happy Coding..........
Feel Free to comment.................Like the website..........by signing through Google+

No comments:

Post a comment