c - 当我们使用新的结构初始化格式时,未列出的成员是否有未指定的值?

标签 c

所以我需要准备一个大型结构:

struct Config {
    int a;
    int b;
    int c;
    struct { int x; int y; } d[40];
};

我想这样填写:

Config config = {
    .a = 3;
    .b = 4;
    .d[0] = {10, 12};
    .d[1] = {14, 16};
};

在此之后,config.cconfig.d[2] 的值是否有未指定的值?还是零?

或者,我需要做:

Config config;
memset(&config, 0, sizeof(config));
config.a = 3;
config.b = 4;
config.d[0].x = 10;
config.d[0].y = 12;
...

最佳答案

它们被初始化为零。

来自 C99 标准,§6.7.8,第 19 项:

The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding anypreviously listed initializer for the same subobject; all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

static 对象的初始化规则在前面的第 10 项中指定:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

关于c - 当我们使用新的结构初始化格式时,未列出的成员是否有未指定的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706116/

相关文章:

c - 这段代码有什么问题

Clock() 不允许我存储在 Clock_t 变量中

c - 如何禁用有关在 GCC 中使用弃用获取的警告?

c - VTune 2013 Profiler 给出错误 : “The Data Cannot be displayed,there is no viewpoint available for data ”

c - 运算符 '|' 不允许的操作数 [MISRA 2012 规则 10.1,必需]

c - 有理数转换为long int

c - 为什么这个 union 的大小是 2 位域?

c++ - 如何为 python 编译 C/C++ 函数

c - 跳过 OpenGL 2.X 并开始学习 OpenGL 3.X 是否更好?

c - Windows 服务作为控制台应用程序运行,但作为服务自动关闭