the "const" qualifier

Karl Heuer karl at haddock.ima.isc.com
Thu Aug 2 02:40:21 AEST 1990


In article <1990Aug1.005200.21645 at ccu.umanitoba.ca> rpjday at ccu.umanitoba.ca writes:
>Section 3.5.3, line 26, we have, "For two qualified types to be
>compatible, both shall have the identically qualified version of a
>compatible type..."  Does "compatible" mean assignment compatible?

No, it means that they really are the exact same type, or could be after
completion.  For example, "void (*f[3])()" and "void (*f[])(double)" are
compatible types, because each can be completed to "void (*f[3])(double)"
(known as the _composite type_).  See 3.1.2.6.

>[deleted stuff that was based on the wrong assumption]
>  Finally, line 12 of 3.5.3, "If an attempt is made to modify an object
>defined with a const-qualified type through use of an lvalue with
>non-const-qualified type, the behavior is undefined."  How would one
>do this anyway?

You can remove const-qualification by using an explicit cast.
	int const i = 10;
	int *p = (int *)&i;
	*p = 20;
The cast itself is legal (though certainly questionable).  The assignment to
`*p' is legal syntactically but not semantically.

Another example is
	extern char const buf[];
	char *p = strchr(buf, c);
where the cast is hidden inside the implementation of strchr().  Logically,
the return type of strchr() is the same as its first actual argument (either
`char const *' or `char *'), but C has no way to declare that.  A similar
problem exists with functions like `memcpy()'.  Caveat emptor.

Karl W. Z. Heuer (karl at kelp.ima.isc.com or ima!kelp!karl), The Walking Lint



More information about the Comp.std.c mailing list