Use of Const keyword in ANSI C

Curt Wohlgemuth curtw at hpcllca.HP.COM
Fri Sep 9 09:25:04 AEST 1988


Clayton Cramer says:

> I'm starting to use the 'const' keyword with the Microsoft V5.1 C compiler.
> I've found something that may be a bug, or it may be that I don't 
> adequately understand 'const'.
> 
> I've defined a structure:
> 
>     typedef struct Tag
>         {
>         const int       A;
>         short           B;
>         const char*     C;
>         } TestType;
> 
>     TestType        Test1 = {10, 10, "test case"};
> 
>     Test1.A = 5;            /* compiler complains about this -- good */
>     Test1.B = 20;           /* compiler accepts this -- fine */
>     Test1.C = "not a test case";    /* compiler accepts this -- bad */
> 
> Should the attempt to set Test1.C to point to another string cause a
> complaint from the compiler?

According to my reading of the ANSI Draft Standard, the delcaration
                      const char *C;
means that C is a pointer to a char object that must be guaranteed to
be constant.  In his scenario,
		      Test1.C = "not a test case";
certainly does not violate this:  the value located at the address that 
holds the string "test case" has not changed.  It still contains the
string "test case", but Test1.C just doesn't refer to it.

In order to prevent the field C to point elsewhere, I think he ought to
declare it as:
		      char * const C;

The ANSI Draft Standard says:
"const int * means (variable) pointer to constant int, and 
int * const means constant pointer to (variable) int."

If he wants a constant pointer, the second form should hold.



More information about the Comp.lang.c mailing list