c++scopename-hiding

Is it well defined to access a variable from an outer scope before it is redefined?


This code compiles with no warnings in gcc-11:

    int i{ 2 };
    {
        std::cout << i;   //prints 2
        int i{ 3 };
        std::cout << i;   //prints 3
    }

Is this well defined or it just happened to work?


Solution

  • Is this well defined or it just happened to work?

    It is well-defined. The scope of a variable declared inside a {...} block starts at the point of declaration and ends at the closing brace. From this C++17 Draft Standard:

    6.3.3 Block scope      [basic.scope.block]

    1     A name declared in a block (9.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (6.3.2) and ends at the end of its block. A variable declared at block scope is a local variable.


    This code compiles with no warnings in gcc-11

    That surprises me. The clang-cl compiler (in Visual Studio 2019, 'borrowing' the /Wall switch from MSVC) gives this:

    warning : declaration shadows a local variable [-Wshadow]

    Using both -Wall and -Wpedantic in GCC 11.2 doesn't generate this warning; however, explicitly adding -Wshadow does give it. Not sure what "general" -Wxxx switch GCC needs to make it appear.