c++scopenestedname-hiding

C++ Nested Scope Accessing


I recently saw this code in cppreference:

string str="global scope";

void main()
{
    string str="main scope";
    if (true){
        string str="if scope";
        cout << str << endl;
    }
    cout << str << endl;
}

Which outputs:

if scope
main scope

This is fine, I understand the whole nested scope thing, and I know that the 'str' inside the if scope will be destroyed when the stack unwinds it at the end of the statement, so it wont be available after that, hence the second print takes the main 'str' as its argument.

However, I know that the main 'str' is in fact available inside the IF, or at least it should be, but the question is how can I access the main 'str' from inside the IF statement?

And how could I access a global 'str' from inside the main and/or the if?

I know it would be simpler to just use different names, but this question is not for a specific practical application, but rather for a better understanding of c++ scopes.


Solution

  • This is a name-hiding issue. And

    how can I access the main 'str' from inside the IF statement?

    Unfortunately it's impossible. There's no way to access these local names being hiden.

    And how could I access a global 'str' from inside the main and/or the if?

    You can use scope resolution operator :: for it, e.g. ::str, which refers to the name str in the global scope.