gcc: why is "abcdef"[3] not a constant (error: initializer element is not constant)

Martin Sebor msebor@redhat.com
Mon May 11 22:58:00 GMT 2015


> Does it really?  I'm not aware of any such language.  There is of
> course implicitly permission for an implementation to do anything
> whatsoever as long as it doesn't break any standard program or fail to
> issue a required dignostic, but that is a very long way from
> "recognzing that a constraint is overly restrictive and unnecessary."
> At least, I can't find it in the standard or the rationale.  Perhaps
> you're aware of some language I've missed.

The text that details the constraints and semantics of constant
expressions is in section 6.6 Constant expressions. Neither
the array subscript operator nor the * operator is listed among
the "shall not contain" operators in the Constraints subsection.
Paragraph 10 of the Semantics subsection then reads:

   An implementation may accept other forms of constant expressions.

This gives permission to implementers to accept and treat as
constant other expressions besides those outlined in the preceding
paragraphs. An example of such an expression is the initializer of
the file scope object B below:

   int A = 1;
   int B = A;

Since no valid initializer expression can change A's value before
it's assigned to B it's possible to substitute it in B's initializer
at compile time. As a result, there's little reason to reject it
except perhaps in a portability or pedantic mode.

> C++11, in particular, has a completely different definition of what
> constitutes a constant expression.  Even some kinds of user-defined
> function calls are allowed, and the OP's exaple is legal.  This is
> doubtless a good thing for users of C++, but isn't relevant here.

Yes. But what's relevant is that both C and C++ implementations
are allowed to use static initialization for constructs that
on strict reading appear to rely on dynamic initialization, as
long as doing so doesn't change the output of a program. That's
just what g++ does in this case. Except when enforcing strict
conformance there's no reason not to expect gcc to do the same.

Martin



More information about the Gcc-help mailing list