two 'const' questions

Rupert Wood
Mon Sep 9 03:08:00 GMT 2002

Ciaron O'Riordan writes:

(I don't have all the answers, but I feel compelled to reply because you
wrote "moo cow" :-) )

> #1 Why does GCC allow writing to 'const' globals and statics?
> Since global and static variables are stored in the data
> segment of an executable the program will always crash when
> run.  A warning is given but I think it should be an error if
> the code is a 100% certain bug.  Any ideas?

Could you give us an example of this? For my test:

    const int cow = 6;
    int moo = cow;

    const char zoot[]="Zoot!";

    int main(void)
        return moo;

I get a warning from GCC's C, even without -Wall,

    const.c: In function `main':
    const.c:8: warning: assignment of read-only location

and an error from g++

    const.c: In function `int main()':
    const.c:8: assignment of read-only location

Now I don't have time to check the standards right now, but I recall
that C's definition of 'const' is less rigarous than C++'s; perhaps
you've come up with a construction that C isn't allowed to assume is
really const memory? If you're talking about a pointer to a constant
string then you could use '-fwritable-strings' or similar; I don't know
how this fits into the standard.

(Or could this be GCC version? I get the same results from both 3.2 and

> #2 Why doesn't GCC allow the use of 'const' variables as
>    initialisation values?
> When I have code declaring two globals like so:
> const int cow = 6;
> int moo = cow;
> I get an error message saying "initialiser element is not
> constant".  Why is this not allowed?  I haven't found anything
> in the standard saying that const variables are not constants.

g++ does allow this but GCC's C does not. Again, I expect this is
related to the C/C++ definitions of const, e.g. vs their definitions of

For comparison, Sun's Forte C compiler rejects it too (but does give an
error for your first point):

    "const.c", line 2: non-constant initializer: op "NAME"
    "const.c", line 8: left operand must be modifiable lvalue: op "="


More information about the Gcc-help mailing list