# Function Arrays

• 06-19-2002
Driveway
Function Arrays
Is it possible to make an array of functions? eg funcarray[2]();
and code the functions later?
• 06-19-2002
Mario
err.... nope :)

If you want to declare a function and "code it later" (aka define it). You can build a prototype ot it.

int sum(int a, int b); //this is the prototype. Note the semicolon

//lot's of code goes here

int sum(int a, int b) //this is the definition of the function.
{
return a+b;
}

This way, even if the function sum() get's called before it's definition, the compiler will know where to look for it.
• 06-19-2002
ninebit
yes you can make an array of function pointers...
• 06-19-2002
Mario
err... I don't thing that's what he asked, ninebit.
I could be wrong, but I got the impression he wants to create a function array, not an array of functions.
• 06-19-2002
ninebit
you would create an ordinary function pointer and then point to that function pointer with an void* in the list. you must know what functions you have in advance and what params to use... if the function is called wrongly with wrong params there is unexpected behaviour... So take great care when you use this...

it would be cool to have this for some kind of commandline type of way to run functions like this:

code:

//parse the line "assign UP 'w'" assign - function, UP and 'w' is params

cmd = "assign"
paramlist("UP", "w")

ExecuteCommand(cmd, paramlist)

in ExecuteCommand:

fncptr = fncMap(cmd);

//find the case where cmd is "assign"
if strcmp(cmd, "assign")
fncptr(paramlist[0], paramlist[1]); // you know the assign function takes 2 params...

anyway.. just a though and highly teorethical...
• 06-19-2002
Driveway
Nine-Bit's right, I want an array of functions. And I know what a prototype is
• 06-19-2002
Mario
well, ok then.

>> Is it possible to make an array of functions? eg funcarray[2]();

You ask for an array of functions, but then give a "function array" (without better words to describe it) as an example...
• 06-20-2002
Salem
Like so?

Code:

```#include <stdio.h> #include <string.h> // pointer to function typedef // it gets too messy to write these out in long form // this just happens to be what strcpy and strcat use typedef char * (*fnptr)(char *, const char* ); // an array of pointers to functions fnptr functions[2] = {     strcpy,     strcat }; int main ( int argc, char *argv[] ) {     char    test[100] = "hello";     int    i;     // calls strcpy then strcat     for ( i = 0 ; i < 2 ; i++ ) {         functions[i]( test, "world " );         printf( "%s\n", test );     }     return 0; }```
• 06-20-2002
rmullen3
You could use a token-pasting macro to achieve a similiar effect.

... maybe.
• 06-20-2002
Unregistered
No ,like this (this probably isn't right)
Code:

```#include <iostream.h> #include <stdio.h> void myfunctions[3](); int main() { for (int i=0; i<4; i++) myfunctions[i]; return 0; } myfunctions[0](i) { //code.... } //other functions```
• 06-20-2002
Driveway