function pointer help needed

Ron Natalie <ron> ron at brl-sem.ARPA
Thu Jan 15 08:52:07 AEST 1987


In article <1327 at loral.UUCP>, jlh at loral.UUCP (Jim Vaxkiller) writes:
> I'm having a little problem with tables of pointers to functions.
> What I want to do is have several functions returning type void,
> then put their addresses into a table and execute the function by
> indexing into the table.  
> The following code fragment illustrates my problem.
> 
> void				/* 2 do nothing routines returning */
> err0()				/*    different data types */
> {}
> int
> err1()
> {}
> static (*ptr_tbl[])() = {	/* table of 2 function pointers */
> 	err0,			/* this is what the compiler hates */
> 	err1
> };

Hold the phone!  Lets look at what you've done.

First..ptr_tbl is declared as an array of pointers to functions
returning INT.  If you don't specify a type it is INT.  You could
fix problem #1 by making it read "static void (*ptr_tbl[])()"

Second.  You do not have a set of functions returning VOID or INT.
You have a combination.  You seem to expect clairvoyance by the
compiler.  It is required that when the compiler calls a function
that it knows what type the function is going to return.  This is
required because calls to functions returning different types may
require different linkages even if you are not going to look at the
return value.  For example, functions returning struct usually want
to write the return value into some allocated area on the stack which
you must set up even if you are casting the return to void.

If you generate a table of mixed types then how is the compiler going
to know which linkage to use for which function.  C has to "typeof"
operator that can be applied to contents of a pointer to find out what
the pointer was pointing to (although some architectures actually support
this).

Make all your functions return the same type.  In this case, void.
If you have a function returning something else, then encapsulate
it in a void function, e.g...

	struct foo goo();

	void vgoo()  {
		(void) goo();
	}

and include vgoo in your table.

-Ron



More information about the Comp.lang.c mailing list