his_dudeness
his_dudeness

Reputation: 43

C++ accessing upper scope instead of global

You can find my code and its output below. What prefix(or something else) should I use in "SOMETHING" to access j in the mid level (j==2) ?

I tried

main::j

But it didn't work.

The Code:

#include <iostream>
int j=3;//global
using std::cout;using std::endl;
int main(){
int j=2;//mid
cout<<"inside general main:\n";
cout<<"cout<<j---"<<j<<endl;//prints 2
cout<<"cout<<::j---"<<::j<<endl;//prints 3
cout<<"inside for loop:\n";
for(int i=0;i<1;i++){
    int j=1;//inside
    cout<<"cout<<j---"<<j<<endl;//prints 1
    cout<<"cout<<::j---"<<::j<<endl;//prints 3
    //cout<<"cout<<::j---"<<SOMETHING<<endl;//prints 2
}
return 0;
}

The Output:

inside general main:
cout<<j---2
cout<<::j---3
inside for loop:
cout<<j---1
cout<<::j---3

Upvotes: 1

Views: 182

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

There is no qualification that refers to a local scope.

Just use different names.

Upvotes: 2

Related Questions