Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why gcc complains "declaration of 'foo' shadows a previous call [-Werror=shadow]"

Tags:

c++

gcc

I have this MCVE:

auto bar() -> double { return 8.0; }

int main()
{
    if ( auto foo = bar() )
    {
        return foo;
    }
    else if ( auto foo = bar() )
    {
        return foo;
    }
}

Compiling it with gcc 7.3 and these options -c -Werror -Wextra -Wall -Wshadow generates these error messages:

test-shadow.cpp: In function ‘int main()’:
test-shadow.cpp:9:17: error: declaration of ‘foo’ shadows a previous local [-Werror=shadow]
  else if ( auto foo = bar() )
                 ^~~
test-shadow.cpp:5:12: note: shadowed declaration is here
  if ( auto foo = bar() )

I don't understand why the 2nd foo is shadowing the 1st definition.

My question:

Why is gcc generating this error? In my eyes the scope of the 1st foo definition is valid only within the if block and therefore the 2nd definition is not shadowing the 1st.

like image 821
Peter VARGA Avatar asked Apr 16 '18 21:04

Peter VARGA


1 Answers

It's basically like this:

auto bar() -> double { return 8.0; }

int main()
{
    { // start of if scope
        auto foo = bar();
        if (foo)
        {
            return foo;
        }
        else
        {
            auto foo = bar(); // this foo shadows previous foo
            if (foo)
            {
                return foo;
            }
        }
    } // end of if scope
}

Hope the code explains it :)

like image 178
fisheye Avatar answered Nov 19 '22 11:11

fisheye