Path: utzoo!attcan!uunet!husc6!cmcl2!adm!smoke!gwyn From: gwyn@smoke.ARPA (Doug Gwyn ) Newsgroups: comp.lang.c Subject: Re: const comparison in C and C++ Message-ID: <8516@smoke.ARPA> Date: 17 Sep 88 20:32:36 GMT References: <709@paris.ICS.UCI.EDU> <8500@smoke.ARPA> <1411@solo3.cs.vu.nl> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 35 In article <1411@solo3.cs.vu.nl> maart@cs.vu.nl (Maarten Litmaath) writes: >In article <8500@smoke.ARPA> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) writes: >\Essentially, C++ "const" means "constant"; ANSI C "const" means "readonly". >Aha! That means the following is correct? >const volatile int * const clock; /* clock is a readonly pointer to */ > /* a readonly and volatile int */ The "const"s mean that you code is not permitted to modify the contents of the variable "clock", nor to modify the int data by indirection via the pointer found in "clock". (The "volatile" means that the contents of the location found by indirection through "clock" are subject to change by agents outside the C virtual machine model, which prevents gung-ho optimizers from picking up the value once then using it ever after without ever fetching it again.) The above declaration at "file scope" would be rather pointless as it calls for "clock" to be initialized with a null pointer, and since you can't subsequently modify it, there's not much point in having it. In an actual application presumably you would supply a suitable address for the initializer. C "const" basically constrains the means of access, so that for example void copy(const char *source, char *destination, unsigned count); is a useful declaration for a function that is guaranteed not to alter storage via its first parameter. However, assuming this represents a block-move function, the destination range is allowed to overlap the source range, because modification of any storage validly accessible via the second parameter is NOT prohibited. If you think about the consequences for code generation when compiling the definition of this example function, it should be clear that one significant class of program bugs can be (must be!) detected AT COMPILE TIME, without adding run-time overhead. That is why this was a suitable addition to C; it fits "the spirit of C". It did take a few iterations to get the specification straightened out.