Initialize static variable with element of const compound literal

≡放荡痞女 提交于 2020-01-06 08:48:17

问题


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 */

EDIT:

The possible duplicacte in the first comment doesn't make sense, because I'm asking explicitly about const literals, and not variables.


回答1:


Yes, an element of a compound literal may be used as an initializer.

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 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.

Paragraph 4 says:

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

Paragraph 7 expands this to:

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 of the other paragraphs prohibit the use of compound literals, so they are permitted.



来源:https://stackoverflow.com/questions/54595387/initialize-static-variable-with-element-of-const-compound-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!