#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
struct emp
{
struct address
{
int a;
};
struct address a1;
};
}
此代码显示警告: -
警告:声明不声明任何内容(默认情况下启用)
以下代码显示没有警告的位置
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
struct emp
{
struct address
{
int a;
}a1;
};
}
为什么'警告'仅显示在第一个代码中?
编译器显示警告的原因是因为它没有看到类型变量的名称 address
你定义的 emp
结构,即使你 做 使用宣布一些东西 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作为成员类型。就像你写的那样:
struct identifier {
type ; // No member name is specified
type a1;
// ...
}
但在第二个示例中,您指定了成员名称:
struct identifier {
type a1; // Member name specified
// ...
}
以下是警告的示例: http://ideone.com/KrnYiE。
显示警告的原因是第一个摘录不合适C - 它违反了符合标准的C编译器 必须 为...生成诊断信息。它违反了 C11 6.7.2.1p2:
约束
- 一个 结构声明 不声明匿名结构或匿名联合的应包含a 结构说明符列表。
这意味着可以写
struct foo {
struct {
int a;
};
};
从内心开始 struct
宣布一个 匿名 结构,即它没有命名。
但在你的例子中 struct address
有一个名字 - address
- 因此它 必须 在结束括号之后有一个声明者列表 - 例如声明者列表 a1
在你的例子中,或更复杂 foo, *bar, **baz[23][45]
。