gcc – 为什么我会收到“警告:缺少成员的初始化程序”? [-Wmissing场-初始化]

我想知道为什么我在一个案例中得到关于初始化的警告,而不是另一个案例.代码位于C源文件中,使用GCC 4.7和-std = c 11.

struct sigaction old_handler, new_handler;

上面使用-Wall和-Wextra生成NO警告.

struct sigaction old_handler={}, new_handler={};
struct sigaction old_handler={0}, new_handler={0};

以上产生警告:

warning: missing initializer for member ‘sigaction::__sigaction_handler’ [-Wmissing-field-initializers]
warning: missing initializer for member ‘sigaction::sa_mask’ [-Wmissing-field-initializers]
warning: missing initializer for member ‘sigaction::sa_flags’ [-Wmissing-field-initializers]
warning: missing initializer for member ‘sigaction::sa_restorer’ [-Wmissing-field-initializers]

我已经阅读了How should I properly initialize a C struct from C++?,Why is the compiler throwing this warning: “missing initializer”? Isn’t the structure initialized?和错误报告,如http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36750.我不明白为什么未初始化的结构不会生成警告,而初始化的结构正在生成警告.

为什么未初始化的结构不会产生警告;为什么初始化的结构会产生警告?

最佳答案
这是一个简单的例子:

#include <iostream>

struct S {
  int a;
  int b;
};

int main() {
  S s { 1 }; // b will be automatically set to 0
             // and that's probably(?) not what you want
  std::cout<<"s.a = "<<s.a<<", s.b = "<<s.b<<std::endl;
}

它给出了警告:

missing.cpp: In function ‘int main()’:
missing.cpp:9:11: warning: missing initializer for member ‘S::b’ [-Wmissing-field-initializers]

程序打印:

s.a = 1, s.b = 0

警告只是提醒编译器S有两个成员,但你只是显式初始化其中一个,另一个将设置为零.如果这是你想要的,你可以放心地忽略那个警告.

在这样一个简单的例子中,它看起来很傻和烦人;如果您的结构有很多成员,那么这个警告可能会有所帮助(捕获错误:错误计算字段数或拼写错误).

Why is the uninitialized structs not generating a warning?

我想这只会产生太多的警告.毕竟,这是合法的,如果您使用未初始化的成员,这只是一个错误.例如:

int main() {
  S s;
  std::cout<<"s.a = "<<s.a<<", s.b = "<<s.b<<std::endl;
}

missing.cpp: In function ‘int main()’:
missing.cpp:10:43: warning: ‘s.S::b’ is used uninitialized in this function [-Wuninitialized]
missing.cpp:10:26: warning: ‘s.S::a’ is used uninitialized in this function [-Wuninitialized]

即使它没有警告我关于s的未初始化成员,它确实警告我使用未初始化的字段.一切都很好.

Why is the initialized structs generating a warning?

只有在您明确但部分初始化字段时,它才会向您发出警告.这提醒一下,struct包含的字段多于您枚举的字段.在我看来,这个警告有多么有用是值得怀疑的:它确实会产生太多的错误警报.嗯,由于某种原因,它默认不亮

转载注明原文:gcc – 为什么我会收到“警告:缺少成员的初始化程序”? [-Wmissing场-初始化] - 代码日志