ANSI C standard library

Stephen Clamage steve at taumet.com
Sun May 5 04:43:47 AEST 1991


meranda at iguana.cis.ohio-state.edu (deron meranda) writes:

>Now, back to the question about implementing strchr() entirely
>in strictly conforming C.  If it is not possible to convert a
>const char * to a plain char *, without loosing to ability to
>dereference the resulting pointer (without a cast), then at
>best, strchr() can only return a pointer which can not be
>directly dereferenced.

You can dereference the pointer.  It is just that the result of
attempting to assign to a const object is undefined.  It is perfectly
legal to cast back and forth between 'T*' and 'const T*', so long as you
bear this in mind.

>From this, it then appears to me that the following program
>segment becomes illegal (or at least undefined):
>   char Array [5] = { 'a', 'b', 'c', 'd', '\0' };
>   char * c;
>   c = strchr( Array, 'd' );
>   if( c ) printf("character is %c", *c );
>Clearly this should be legal under a conforming implementation

And so it is.  You are nowhere assigning through a pointer to const.

>Therefore, am I correct in saying that strchr
>can not correctly be written entirely in strictly conforming C?

No, there is no problem with writing strchr in strictly conforming C.
All of the casting and dereferencing within strchr is perfectly ok.
If you in fact pass strchr a const string and attempt to assign
through the returned pointer, the result is undefined.

char *p;	/* pointer to non-const */
const char *pc;	/* pointer to const */

char *s = strchr(p, 'a');	/* ok */
char *t = strchr(pc, 'a');	/* ok */
*s = 'A';			/* ok -- s points to a non-const char */
*t = 'A';			/* not strictly conforming */

The last line above is in general not detectable by a compiler as not
strictly conforming (the effect might be spread across several compilation
units).  The effect of assigning to what 't' points to (some place in
what 'pc' points to) is undefined.  In fact, 'pc' might point to a
non-const string and this is really ok.  We can only know, however, that
what 'pc' points to is not supposed to be modified.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.std.c mailing list