Bug in new K&R?

Doug Gwyn gwyn at brl-smoke.ARPA
Sun May 8 08:55:58 AEST 1988


In article <44200009 at uicsrd.csrd.uiuc.edu> mcdaniel at uicsrd.csrd.uiuc.edu writes:
>	qsort((void **) lineptr, 0, nlines-1,
>	  (int (*)(void*,void*))(numeric ? numcmp : strcmp));
>Are those two casts portable---is it guaranteed that "void *" and
>"char *" have the same internal representation?

Yes, the proposed C standard requires that.

>Whether or not it's legal, the type punning above is obscene.

You won't get any argument from me there!

numcmp and strcmp are pointers to what in ANSI C parlance are termed
"compatible types", so there is not a type mismatch between the
operands of the ?: operator, as one might think at first.  It takes
some degree of language lawyer virtuosity to unravel the constraints
in the proposed standard to discover that this usage is in fact legal.
The reason for the cast is that it does not appear to be specified
what the "composite type" is when a char * and a void * collide, so
the cast ensures that whatever the type is, it is turned into the
right thing to feed to qsort().  Presumably this oversight is one of
the things that will be fixed in the next draft of the standard.

The more usual solution is to define numcmp() with void * parameters
and apply explicit casts at the beginning of its function body.



More information about the Comp.lang.c mailing list