Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading