如何修复gcc警告:缺少'struct <anonymous>'字段的初始值设定项?

时间:2016-03-19 23:02:01

标签: gcc gcc-warning

我有一个包含匿名结构的union typedef。在尝试初始化时,我总是会收到关于字段缺少初始值设定项的gcc 4.9.2(-Wall -Wextra -pedantic)的警告。但它似乎按预期工作。下面初始化变量的方式有问题吗?

#include <stdio.h>

typedef union {
  unsigned int raw;
  struct {
    unsigned short hue;
    unsigned char  saturation;
    unsigned char  value;
  };
} HSV;

int main() {
    HSV color = {.hue = 1, .saturation = 2, .value = 4};

    printf("hue: %d, saturation: %d, value: %d, raw: %08X\n", color.hue, color.saturation, color.value, color.raw);
}

编译gcc时会发出一些警告。

$ gcc -Wall -Wextra -pedantic -std=gnu11 main.c 
main.c: In function 'main':
main.c:13:2: warning: missing initializer for field 'saturation' of 'struct <anonymous>' [-Wmissing-field-initializers]
  HSV color = {.hue =   1, .saturation = 2, .value = 4};
  ^
main.c:7:20: note: 'saturation' declared here
     unsigned char  saturation;
                    ^
main.c:13:2: warning: missing initializer for field 'value' of 'struct <anonymous>' [-Wmissing-field-initializers]
  HSV color = {.hue =   1, .saturation = 2, .value = 4};
  ^
main.c:8:20: note: 'value' declared here
     unsigned char  value;
                    ^
$ ./a.out 
hue: 1, saturation: 2, value: 4, raw: 04020001

0 个答案:

没有答案