Calling functions by address

Chris Torek chris at mimsy.UUCP
Wed Aug 31 15:22:06 AEST 1988


In article <626 at dinl.mmc.UUCP> noren at dinl.uucp (Charles Noren) writes:

Your syntax needs work:

>typedef void (*func)()  funcarray;

`typedef void (*func)();' or `typedef void (*funcarray[])()'.

>void func1(), func2(), func3(),...   /* Function Prototypes */

These are declarations, but not prototype declarations.  (There is
a substantial difference.)

>funcarray addressarray [] = {
>   func1, func2, func3,...
>}

If the typedef includes the []s, the declaration should not; conversely,
if the typedef does not, the declaration should.  This would work given

    typedef void (*funcarray)();

although I think this is a misleading name (there is no array here).

>...and then execute this function to call function by address code:
>
>void execute (array, code)
>funcarray array[];
>int       code;
>{
>  void (*function) ();
>
>  function = array[code];
>  (*function)();
>}

This syntax is correct.

>...the calling code would look like:
>
>  execute (addressarray, code);

The multiple levels of calling are unnecessary.  If `a' is an object of
type `array N of pointer to function (args) returning void', then the
syntax to call that function is

	(*a[i])(args);

so the call to `execute(addressarray, code)' can be replaced with
`(*addressarray[code])()'.  Note that subscript `[]' binds more tightly
than indirection `*', so the format (*(a[i]))(args) suggested in
another article is also correct.  The formats a[i](args) (and,
equivalently, (a[i])(args)) are NOT correct by K&R 1st ed., although
they have been legitimised in the three draft proposed ANSI standards
submitted for public review, and are accepted by numerous compilers.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list