简体   繁体   中英

struct name not shadowing variable name

I notice that the following code compiles with recent compilers:

int main()
{
    int x;
    struct x;
    x = 210;                  // ←
}

As I recall it didn't compile some years ago.

Were the lookup rules changed in C++11 or C++14 to make this code “work” (thus breaking use of struct variable_name; as a means to ensure no use of the variable in the following code)?


Update : Evidently I remembered incorrectly. I have verified that the code compiled OK even with Visual C++ 2010. However, when used for parameters the struct name is in an inner scope, and shadows, like in this code:

void foo( int x )
{
    struct x;
    x = 210;                  // ← Error
}

int main()
{
}

Accordingly I have selected as “solution” the answer that there was no change; the rules were always like this.

[basic.scope.hiding]/2 A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

This language has existed since C++98. If you've seen a compiler that worked differently, that compiler was pre-standard, or just plain buggy.

What you did was forward declarations of struct x . You did not declared and new variable called x . Example:

struct foo;
int foo;
struct foo {
    int foo;
};
struct foo thisisfoovariable;

Above are declarations of only two variables: foo (of type int ) and thisisfoovariable, which type is struct foo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM