-->

Initialize static variable with element of const c

2019-08-26 05:21发布

问题:

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.