使用 const 复合文字的元素初始化静态变量

Initialize static variable with element of const compound literal

const 复合文字是 static 变量的有效初始值设定项吗?

#define COMPOUND    ((const int [2]){1, 2})

static const int    x   = COMPOUND[0];
/* static const int x   = 1; should be equivalent */

编辑:

第一条评论中可能的重复没有意义,因为我明确询问的是 const 文字,而不是变量。

是的,复合文字的元素可以用作初始值设定项。

C 2018 6.7.9 4 告诉我们初始化器必须是什么:

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

6.6告诉我们常量表达式可能是什么。第 3 段说:

Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.

第 4 段说:

Each constant expression shall evaluate to a constant that is in the range of representable values for its type.

第 7 段将其扩展为:

More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following:

  • an arithmetic constant expression,
  • a null pointer constant,
  • an address constant, or
  • an address constant for a complete object type plus or minus an integer constant expression.

None 其他段落禁止使用复合字面量,所以允许使用。