www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/07/28/18:47:48

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Array of Functions
Date: Mon, 28 Jul 1997 10:09:16 -0700
Organization: Alcyone Systems
Lines: 69
Message-ID: <33DCD23C.6B1EE721@alcyone.com>
References: <19970715 DOT 215516 DOT 5183 DOT 0 DOT chambers DOT ben AT juno DOT com> <33CD32FD DOT 3A6 AT cs DOT com>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

John M. Aldrich wrote:

> Hmm... we can't tell what your problem is without a specific code
> sample.  But if I were to declare an array of functions, this is how I'd
> do it:
> 
> typedef int (*ARRAY_FUN) ( DATA data, int foo );

Small pedantic nitpick:  You can have arrays of function _pointers_, not
functions.

Note that that's not merely a semantic difference; you can make a typedef
to a function:

    typedef int (Function)(DATA, int);

And define a pointer to it:

    Function *fp;

And an array of function pointers:

    Function *afp[];

But not an array of functions:

    Function af[]; /* error */

> int (*(function_list[])) ( DATA data, int foo ) = 

Note that you don't need the extra parentheses here, since [] binds more
tightly than *:

    int (*functionList[]))(DATA, int);

> To access the array from a function, follow this example:
> 
>     (*function_list[i]) ( data, foo );

Final detail:  dereferencing the function pointer to call it is actually
unnecessary (but if it's your style go right ahead).  It's not only
unnecessary, it doesn't do anything:

    (***********functionList[i])(data, foo);

is a perfectly legal call, as is 

    (functionList[i])(data, foo);

In fact, if you had a function pointer and wanted to call it, it would
look like you were calling any other function, although since you're
calling through a function pointer, the actual function called may change:

    Function *fp;

    fp(data, foo); /* looks like any other call */

Just providing a little bit more information about function pointers;
John's advice was right on the money.  (Function pointers are one of the
more abstract and difficult-to-understand concepts in C, especially since
the syntax is awkward.)

-- 
       Erik Max Francis, &tSftDotIotE / email / max AT alcyone DOT com
                     Alcyone Systems /   web / http://www.alcyone.com/max/
San Jose, California, United States /  icbm / 37 20 07 N  121 53 38 W
                                   \
   "Love is not love which alters / when it alternation finds."
                                 / William Shakespeare, _Sonnets_, 116

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019