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

Martin Sebor msebor@redhat.com
Mon May 11 15:44:00 GMT 2015


>> I just did not understand the idea behind this restriction. Perhaps
>> there is a good reason (beside the standard) for this.
>
> I don't think there is.  There has to be some limit on how far to do
> constant propagation.  This limit is necessarily arbitrary: there is
> no obvious point at which to say "this far, and no further."

The C constraint that initializers of objects with static
storage duration be constant expressions is in place to
keep the implementation of program startup as simple as
possible and avoid dependencies between object values at
this stage.

There are cases when this constraint is overly restrictive
and unnecessary. The C standard recognizes that and permits
implementations to accept other forms of constant expressions
(such as "abcdef"[3]) beyond those explicitly listed.

The same constraint doesn't exist in C++ because the language
has dynamic initialization of such objects as a general feature
(with all its benefits and liabilities).

Martin



More information about the Gcc-help mailing list