Bug#225935: gcc-3.3: function static variable initialization allowed with pure functions only when -O is used
On 3 Jan 2004, Falk Hueffner wrote:
> Britton Leo Kerin <email@example.com> writes:
> > static char *const foo = "baz";
> > static int foo_len = strlen(foo);
> > /* static int foo_len = an_impure_function(); */
> > greenwood$ gcc test_const.c
> > test_const.c: In function `main':
> > test_const.c:14: error: initializer element is not constant
> > greenwood$
> > Replaceing the strlen call with a call of an impure function
> > (commented out above) results in the above error whether or not -O is
> > used. It seems to me that pure function should either always be
> > usable in this way regardless of -O (and C200? should endorse pure
> > attribute and mandate the behavior), or never be supported.
> This has nothing to do with pureness; the standard mandates a constant
> expression as initializer, and when optimizing, gcc replaces
> "strlen(foo)" with 3. Correct handling of constant expressions in gcc
> is mostly unimplemented, see http://gcc.gnu.org/PR456.
It can only do that because it knows strlen is pure, thats the point of
pureness. If the standard says constant only, gcc should choke on
strlen() with or without optimization.
> I suggest we either mark this as forwarded pointing to above bug, or
> close it, since it is IMHO a pretty minor issue...
I don't entirely understand that bug report, but I don't think it is the
same since all the code in my example is evaluated. I don't agree that
the bug is minor, it has already cost me several hours of confusion. It
lets you use the nice construct 'some_constant_string = "whatever"; static
length_of_some_constant_string = strlen(some_constant_string);' instead of
cutting and pasting the string constant only when optimization is on,
which is confusing.