two 'const' questions

Ciaran O'Riordan
Mon Sep 9 10:18:00 GMT 2002

On <earlier> "Rupert Wood" <> wrote:

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

my favourite meaningless variable names.

> > #1 Why does GCC allow writing to 'const' globals and statics?
>Could you give us an example of this?

const int cow = 10;  | int main()               | int main()
		     | {                        | {
int main()           |   const static cow = 6;  |   const cow = 6;
{		     |   cow = 7;               |   cow = 7;
  cow = 11;	     |   return 0;              |   return 0;
  return 0;	     | }                        | }
}		     |                          |

When compiled and run (with gcc 2.95.3 or 3.1.1), the first and second
column will segfault.  The third column runs without crashing (and a
larger example shows that 'cow' does received the value 7).  All
produce warnings.

>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;

>From the standard (section 6.7.3 Type Qualifiers):

[...] they specifiy the assumtions a compile can and must make when
accessing an object through an lvalue.
The syntax and semantics of 'const' were adapted from C++
const    No writes through this lvalue.  In the absense of this
         qualifier, writes may occur through this lvalue.

@end quotation

pTo me, that says you cannot write to a const variable and by "cannot"
I mean "it is an error to".

> > #2 Why doesn't GCC allow the use of 'const' variables as
> > initialisation values?

> > I get an error message saying "initialiser element is not
> > constant".

>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 literal.

hmm, I think I'll send a mail to one of the lists the developers use
and file a bug report.  If nothing else, the error message is

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

I haven't found an answer to #2 in the standard yet...

Ciaran O'Riordan

Chat with friends online, try MSN Messenger:

More information about the Gcc-help mailing list