dimanche 3 mars 2019

Accessing variables with same name but different nesting depth [duplicate]

This question already has an answer here:

So I have a kind of theoretical question regarding variable accessing. I know that it is an absolutely terrible idea, but for the sake of argument let's say that you have written the following (useless) program:

int a = 100;
int main(){
    int a = 90;
    {
       int a = 80;
       {
           int a=70;
           std::cout << somethingGoesHere;
       }
    }
return 0;
}

If I now replace somethingGoesHere with a, and run the program, the output will be 70, since the program will be using the a with the "closest" scope. Furthermore, if i replace somethingGoesHere with ::a, the output will be 100, since the unary scope resolution operator lets you access the global variable with the given name.

Now, what if I want to print any of the two other a's ?, for example the a with value 80, in the same output statement. Is that possible somehow? I mean, is there some operator that lets you access a variable which has a nesting layer depth one less than the one you are currently in? (Or lesting layer depth k less the one you are currently in?)

Thanks, R

Aucun commentaire:

Enregistrer un commentaire