Function pointer casts in ANSI C

Lars Henrik Mathiesen thorinn at skinfaxe.diku.dk
Thu Nov 29 22:01:14 AEST 1990


ANSI C guarantees that a pointer to a function can be cast to another
function pointer type and back, and retain its value. However, if it
is used ``at a wrong type'', the results are undefined.

My question is: Can a conforming compiler generate a warning for casts
(and arguments) that will ``go wrong'' but not for those that work?
I'm thinking of something like this:

	void myqsort(void **, int (*)(void *, void *));

	typedef struct { ... } data;

	int foo(data * a, data * b) { ... }

	int main() {
	    data *sort[NSORT];

	    ...
	    myqsort(sort, foo);
	    ...
	}

This will work as expected if and only if exactly the same calling
sequence is generated for the following two calls to foo:

	    void *a, *b;

	    foo(a, b);
	    ( (void (*)(void *, void *))foo )(a, b);

If it works, the compiler should warn about a non-portable cast; if it
doesn't work, the warning should say 'cast between pointers to
functions with incompatible calling sequences' or something. And the
former might be easier to turn off than the latter.

The questions are: Do any compilers implement this test? Would it be
difficult to do so in, e.g., gcc? And is it legal for a conforming
ANSI C compiler to diagnose only ``bad'' casts?

--
Lars Mathiesen, DIKU, U of Copenhagen, Denmark      [uunet!]mcsun!diku!thorinn
Institute of Datalogy -- we're scientists, not engineers.      thorinn at diku.dk



More information about the Comp.lang.c mailing list