声明没有声明任何内容:警告?

#include  #include  #include  int main() { struct emp { struct address { int a; }; struct address a1; }; } 

此代码显示警告: –

警告:声明不声明任何内容(默认情况下启用)

以下代码显示没有警告的位置

 #include  #include  #include  int main() { struct emp { struct address { int a; }a1; }; } 

为什么’警告’仅显示在第一个代码中?

编译器显示警告的原因是因为它没有看到为emp结构定义的类型address变量的名称,即使你在下一行使用address声明了某些东西,但我想编译器是不够聪明,无法弄明白。

如您所示,这会产生警告:

 struct emp { struct address {}; // This statement doesn't declare any variable for the emp struct. struct address a1; }; 

但不是这个:

 struct emp { struct address {} a1; // This statement defines the address struct and the a1 variable. }; 

或这个:

 struct address {}; struct emp { struct address a1; //the only statement declare a variable of type struct address }; 

struct emp {}没有显示任何警告,因为此语句不在struct defintion块中。 如果您确实将其放入其中一个,那么编译器也会显示警告。 以下将显示两个警告:

 struct emp { struct phone {}; struct name {}; }; 

结构定义的语法是:

 struct identifier { type member_name; // ... }; 

如果在结束大括号之后添加标识符,则声明具有该定义结构的变量。

在第一个示例中,编译器将address结构视为成员类型。 就像你写的那样:

 struct identifier { type ; // No member name is specified type a1; // ... } 

但在第二个示例中,您指定了成员名称:

 struct identifier { type a1; // Member name specified // ... } 

以下是警告的示例: http : //ideone.com/KrnYiE 。

显示警告的原因是第一个摘录不正确C – 它违反了约束条件,符合标准的C编译器必须为其生成diagnostisc消息。 它违反了C11 6.7.2.1p2 :

约束

  1. 不声明匿名结构或匿名联合的结构声明应包含struct-declarator-list

这意味着可以写

 struct foo { struct { int a; }; }; 

因为内部struct声明了一个匿名结构,即它没有被命名。

但是在你的例子中, struct address有一个名称 – address – 因此它必须在结束括号之后有一个声明符列表 – 声明者列表例如是你的例子中的a1 ,或者更复杂的foo, *bar, **baz[23][45]