ANSI C and function prototypes

John Gilmore gnu at hoptoad.uucp
Thu Feb 13 23:34:04 AEST 1986


In article <250 at hadron.UUCP>, jsdy at hadron.UUCP (Joseph S. D. Yao) writes:
> In article <681 at harvard.UUCP> steve at harvard.UUCP (Kaufer - Lopez - Pratap) writes:
> >	Let's say I want to write a 'dispatcher' routine that is 
> >passed a code number and a pointer to a function to call.
> >I wish to use a prototype to make sure that I am always passing 
> >two arguments, the first of which is an int and the 
> >second of which is a function pointer.  
> >	I might define the prototype as:
> >	dispatcher(int code, void (*disp_func)());
> >	Is there any way to prototype the second argument as a pointer to
> >a function returning 'anything'?
> 
> If 'anything' is limited to pointers, you can say:
> 	int dispatcher(int code, void *(*disp_func)());
> as I understand it.

Not true.  When you declare the return type of a function (or function
pointer), what you say has to agree with what it does.  This is not a
type-cast, it's a declaration, folks -- if you declare "int foo" in one
file you'd better not call it "float foo" in another.  You can't cast a
"function returning int" into a "function returning void *".  You CAN
cast its *result* after it has returned, but you can't cast the *function*.

It matters because compilers may need to allocate stack or register
space for the result of calling thru the function pointer.  Depending
on the type of the result (of the actual function called), more or less
space might need to be allocated by the caller.  I can think of good
reasons for having different return conventions for each of these
different return types: struct, int, long, int *, char * or void *.
Consider a sufficiently odd machine (word addressed, 16 bit words,
separate address&data regs).  If you call a function that doesn't match
your function pointer declaration, the registers or stack can get
clobberred.  Definitely nonportable.

The only safe bet is to make sure that all the functions which will be
called through this function pointer *do indeed* return the type you
declared the pointer with.
-- 
John Gilmore  {sun,ptsfa,lll-crg,ihnp4}!hoptoad!gnu   jgilmore at lll-crg.arpa



More information about the Comp.lang.c mailing list