17

gcc -std=c99 -Wextra这段代码编译:

#include <stdio.h>

struct T {
    int a;
    int *b;
    int c;
};

int main(void)
{
    struct T t = {.b = ((int []){1, 1})};

    printf("%d\n", t.b[1]);
    return 0;
}

给我一个警告:

demo.c:11:12: warning: missing initializer for field ‘c’ of ‘struct T’ [-Wmissing-field-initializers]
     struct T t = {.b = ((int []){1, 1})};
            ^
demo.c:6:9: note: ‘c’ declared here
     int c;
         ^

但是指定的初始化程序应该将其余成员初始化为零,即使它们被省略。

为什么要发出警告?(clang编译相同的代码没有警告)

gcc version 6.3.0 20170516 (Debian 6.3.0-18) 
clang version 3.8.1-24 (tags/RELEASE_381/final)
4

2 回答 2

2

它看起来像一个 gcc “一致性错误”,这里是相关的代码片段gcc/c/c-typeck.c

 7436   /* Warn when some struct elements are implicitly initialized to zero.  */
 7437   if (warn_missing_field_initializers
 7438       && constructor_type
 7439       && TREE_CODE (constructor_type) == RECORD_TYPE
 7440       && constructor_unfilled_fields)
 7441     {
 7442         bool constructor_zeroinit =
 7443          (vec_safe_length (constructor_elements) == 1
 7444           && integer_zerop ((*constructor_elements)[0].value));
 7445
 7446         /* Do not warn for flexible array members or zero-length arrays.  */
 7447         while (constructor_unfilled_fields
 7448                && (!DECL_SIZE (constructor_unfilled_fields)
 7449                    || integer_zerop (DECL_SIZE (constructor_unfilled_fields))))
 7450           constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields);
 7451
 7452         if (constructor_unfilled_fields
 7453             /* Do not warn if this level of the initializer uses member
 7454                designators; it is likely to be deliberate.  */
 7455             && !constructor_designated
 7456             /* Do not warn about initializing with ` = {0}'.  */
 7457             && !constructor_zeroinit)
 7458           {
 7459             if (warning_at (input_location, OPT_Wmissing_field_initializers,
 7460                             "missing initializer for field %qD of %qT",
 7461                             constructor_unfilled_fields,
 7462                             constructor_type))
 7463               inform (DECL_SOURCE_LOCATION (constructor_unfilled_fields),
 7464                       "%qD declared here", constructor_unfilled_fields);
 7465           }
 7466     }

代码的意图似乎是警告任何属性构造函数是否具有未填充字段。您没有收到有关元素“a”的警告这一事实可能是这里的“一致性错误”。

如果-Wextra打算打开缺少初始化程序的警告,那么它有。问题是,“缺少初始化程序警告”是否应该排除省略的属性?似乎 gcc 和 clang 不同意这一点 - 他们可能会这样做吗?

这可能不是您正在寻找的答案.. 但希望它有助于您了解情况。:)。GCC 团队有一个一致性错误,但在这些情况下,他们的代码意图似乎是警告的,而根据经验,clang 不会。

于 2020-02-11T15:39:53.443 回答
0

为什么要发出警告?

因为-Wmissing-field-initializers是由设置的,而您在调用-Wextra中设置了后者。gcc

-Wextra很挑剔,-Wmissing-field-initializers甚至不是-Wall.

仅省略一些字段初始值设定项但并非全部是错误的来源。在具有数百个元素的数组/结构中,您只是在初始化其中一些元素,那么人类几乎不可能通过查看代码来掌握它。

于 2020-01-31T11:24:49.490 回答