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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With