const comparison in C and C++

Doug Gwyn gwyn at smoke.ARPA
Sun Sep 18 06:32:36 AEST 1988


In article <1411 at solo3.cs.vu.nl> maart at cs.vu.nl (Maarten Litmaath) writes:
>In article <8500 at smoke.ARPA> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) 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.



More information about the Comp.lang.c mailing list