gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:49:46 24 4
gpt4 key购买 nike

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.

其他段落均未禁止使用复合文字,因此它们是允许的。

关于c - 使用 const 复合文字的元素初始化静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54595387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com