用const复合文字的元素初始化静态变量 [英] Initialize static variable with element of const compound literal
问题描述
const
复合文字是否是static
变量的有效初始值设定项?
Is a const
compound literal a valid initializer for a static
variable?
#define COMPOUND ((const int [2]){1, 2})
static const int x = COMPOUND[0];
/* static const int x = 1; should be equivalent */
第一个注释中可能的重复项没有任何意义,因为我明确询问的是const
文字,而不是变量.
The possible duplicacte in the first comment doesn't make sense, because I'm asking explicitly about const
literals, and not variables.
推荐答案
是的,复合文字的元素可以用作初始化程序.
Yes, an element of a compound literal may be used as an initializer.
C 2018 6.7.9 4告诉我们必须使用什么初始化器:
C 2018 6.7.9 4 tells us what initializers must be:
对于具有静态或线程存储持续时间的对象,初始化器中的所有表达式均应为常量表达式或字符串文字.
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段说:
6.6 tells us what constant expressions may be. Paragraph 3 says:
常量表达式不得包含赋值,递增,递减,函数调用或逗号运算符,除非它们包含在未求值的子表达式中.
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:
- 算术常数表达式,
- 空指针常量,
- 地址常数,或
- 用于完整对象类型的地址常量,加上或减去整数常量表达式.
其他段落均禁止使用复合文字,因此允许使用它们.
None of the other paragraphs prohibit the use of compound literals, so they are permitted.
这篇关于用const复合文字的元素初始化静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!