1
#include <iostream>

using std::cout;
using std::endl;

int a {1};

int main()
{
    int a {2};

    {
        int a {3};
        cout << ::a << endl;
        cout << a << endl;
    }

    return 0;
}

the first output is 1, it's the value of a that defined before function main()

so is there any way to output the second a that defined in function main() in the inner block ? thanks!

Joseph D.
  • 11,804
  • 3
  • 34
  • 67
TwenteMaster
  • 148
  • 2
  • 12
  • [**TL;DR**](https://stackoverflow.com/questions/7047621/is-there-a-way-to-access-the-value-of-a-local-variable-that-has-become-hidden-in#comment8428868_7047655). – StoryTeller - Unslander Monica Jun 17 '18 at 09:23
  • @StoryTeller I think the post you tagged is different to this. – Joseph D. Jun 17 '18 at 09:24
  • 1
    @codekaizer - It's not. It's the exact same problem. The only difference is the more fleshed out comparison to the variable at global scope – StoryTeller - Unslander Monica Jun 17 '18 at 09:24
  • @StoryTeller, the answers seems a little bit vague - like it's unsupported or inaccessible. So would that mean my answer is wrong? – Joseph D. Jun 17 '18 at 09:27
  • @codekaizer - The answers all point out that there is no direct language support, and present workarounds (the good ones anyway). I don't see why yours would be wrong. It's an acceptable workaround. I also think it would belong to the duplicate just as much as it can belong here (which is why I firmly believe in the other post being a good dupe candidate). – StoryTeller - Unslander Monica Jun 17 '18 at 09:29
  • @StoryTeller, thanks for clarifying about the *workaround*. – Joseph D. Jun 17 '18 at 09:30

1 Answers1

1

so is there any way to output the second a that defined in function main() in the inner block ?

a{2} and a{3} are both in block-scope.

Thus, a{3} shadows a{2} in the inner-block.

To output the a{2} you just need to move the point-of-declaration of a{3}.

int a {2};

{
    cout << ::a << endl;
    cout << a << endl; // a{2} will be used here
                       // since a{3} is not defined here yet.
    int a {3};
    cout << a << endl; // a{3} will be used here
                       // since it's already defined at this point
}
Joseph D.
  • 11,804
  • 3
  • 34
  • 67