+ 1

Can (::) operator be used for more than 2 variables with same name at different scopes.

If I have a function and in that function I have an if or some other block and I have a global variable i, a variable i local to the function and a variable i local to the if block. Can i use all the variables inside the if block.

22nd Jul 2018, 5:23 AM
Mukul
Mukul - avatar
2 Réponses
+ 5
" Can (::) operator be used for more than 2 variables with same name at different scopes. " Scope operator just communicates with global scope variables. No matter how many nested scope you want to include in your code, :: operator can only talk to the global ones. ●● Example ●● // Global scope int x = 100; int y = 200; int main() { // Outer scope L0 int x = 10; int y = 20; { // Inner scope L1 int x = 1; int y = 2; { // Inner scope L2 int x = -1; int y = -2; cout << "L2 " << ::x << ::y << endl; } cout << "L1 " << ::x << ::y << endl; } cout << "L0 " << ::x << ::y << endl; } Output: L2 100200 L1 100200 L0 100200
22nd Jul 2018, 6:42 AM
Babak
Babak - avatar
+ 6
So basically: int i; void function () { int i; if (...) { int i; // invoke all three i here } } ... which is as answered in this SO thread. https://stackoverflow.com/questions/8358628/is-there-any-way-to-access-a-local-variable-in-outer-scope-in-c
22nd Jul 2018, 5:50 AM
Hatsy Rei
Hatsy Rei - avatar