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

kev*_*mes 12 c struct warnings

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
    struct emp
    {
        struct address
        {
              int a;
        };
        struct address a1;
    };
}
Run Code Online (Sandbox Code Playgroud)

此代码显示警告: -

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

以下代码显示无警告的位置

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
    struct emp
    {
        struct address
        {
             int a;
        }a1;
    };
}   
Run Code Online (Sandbox Code Playgroud)

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

jua*_*rro 9

编译器显示警告的原因是因为它没有看到addressemp结构定义的类型变量的名称,即使你确实address在下一行声明了某些东西,但我猜编译器不够智能想出这个.

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

struct emp {
  struct address {}; // This statement doesn't declare any variable for the emp struct.
  struct address a1;
};
Run Code Online (Sandbox Code Playgroud)

但不是这个:

struct emp {
  struct address {} a1; // This statement defines the address struct and the a1 variable.
};
Run Code Online (Sandbox Code Playgroud)

或这个:

struct address {};

struct emp {
  struct address a1; //the only statement declare a variable of type struct address
};
Run Code Online (Sandbox Code Playgroud)

struct emp {}不显示任何警告,因为这种说法是不是结构确定指标块内.如果你把它放在其中一个中,那么编译器也会显示一个警告.以下将显示两个警告:

struct emp {
  struct phone {};
  struct name {};
};
Run Code Online (Sandbox Code Playgroud)


Ant*_*ala 6

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

约束

  1. 一个结构声明不声明匿名结构或匿名联合应包含结构说明符列表

意思是可以写

struct foo {
    struct {
          int a;
    };
};
Run Code Online (Sandbox Code Playgroud)

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

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


rul*_*lof 5

结构定义的语法是:

struct identifier {
    type member_name;

    // ...

};
Run Code Online (Sandbox Code Playgroud)

如果您在右花括号之后添加标识符,那么您就是在声明一个具有该定义结构的变量。

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

struct identifier {

    type ; // No member name is specified
    type a1;

    // ...

}
Run Code Online (Sandbox Code Playgroud)

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

struct identifier {

    type a1; // Member name specified

    // ...

}
Run Code Online (Sandbox Code Playgroud)

这是警告的示例:http : //ideone.com/KrnYiE