4

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
J3STER
  • 1,027
  • 2
  • 11
  • 28

2 Answers2

5

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • thanks, are you 100% sure its imposible (first question)> – J3STER Jan 25 '17 at 03:01
  • 1
    @J3STER Yes, I am. There's no way to access these local names being hiden. – songyuanyao Jan 25 '17 at 03:06
  • I'll second that, local variables are inaccessible to everything outside its scope. Also local variables are destroyed on exit of the scope so I don't see how one would access the object anyway ? – PaulHK Jan 25 '17 at 03:09
  • 2
    @PaulHK the question is how can the inner scope access the outer scope's `str` variable when the inner scope hides that variable with its own inner `str` variable. And the answer is it is not possible. Your comment reads like you think the outer scope is trying to access the inner scope's variable instead. Which is also not possible. – Remy Lebeau Jan 25 '17 at 03:42
3

The if block can't refer to the str variable that is defined in main(), unless you change the name of one of the variables. Accessing outer variables of the same name as inner variables is not possible.

However, global variables can be accessed using the :: operator.

Although, a work around is possible using pointers:

string str = "global-scope";

void main()
{
    string str = "main scope";
    string *ptrOfStr = &str;
    if (true){
        string str = "if scope";
        cout << str << endl;
        cout << "Value of str in main block : " << *ptrOfStr;
    }
    cout << str << endl;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Tushar Gandhi
  • 237
  • 4
  • 17