Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!ucsd!ucsdhub!hp-sdd!hplabs!hpda!hpcuhb!hpcllla!hpcllca!curtw From: curtw@hpcllca.HP.COM (Curt Wohlgemuth) Newsgroups: comp.lang.c Subject: Re: Use of Const keyword in ANSI C Message-ID: <7330009@hpcllca.HP.COM> Date: 8 Sep 88 23:25:04 GMT References: <441@optilink.UUCP> Organization: HP NSG/ISD California Language Lab Lines: 41 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.