Thoughts on `const' parameters

Henry Spencer henry at utzoo.uucp
Fri Dec 2 06:31:18 AEST 1988


In article <957 at vsi.COM> friedl at vsi.COM (Stephen J. Friedl) writes:
>     Let's say that I have a function like strchr(), which
>might be written as:
>
>	char *strchr(const char *string, int ch)	...
>
>     What prevents me from passing a const argument (say, a string
>in readonly memory), locating my desired character within the string,
>and then storing a NUL there?  ...

Unless the compiler is very smart, it can't prevent this, but the effect
of the store is undefined because the original object was declared const.
(This essentially means that you shouldn't do it but X3J11 felt that a
rule against it would be unenforceable.)

The problem is that "const" is used for two different things:  creating
invariant objects, and declaring that a function is not allowed to modify
parameters (ones passed via pointers).  What is really wanted is a way
to declare strchr as taking a read-only parameter that might or might
not be const, and returning a value that is just as const as the parameter.
You might be able to do this (by using overloading and two functions) in
C++, but you can't do it in C.

So X3J11 const is a compromise, which accomplishes its most prominent
objectives but cannot fully protect const objects in the presence of
pointers.
-- 
SunOSish, adj:  requiring      |     Henry Spencer at U of Toronto Zoology
32-bit bug numbers.            | uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.std.c mailing list