Is it possible to make an array of functions? eg funcarray[2]();
and code the functions later?
Printable View
Is it possible to make an array of functions? eg funcarray[2]();
and code the functions later?
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.
yes you can make an array of function pointers...
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.
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:
cmdline> assign UP 'w'
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...
Nine-Bit's right, I want an array of functions. And I know what a prototype is
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...
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;
}
You could use a token-pasting macro to achieve a similiar effect.
... maybe.
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
That was me, didn't log in
Use function pointers. Arrays and pointers generally are the same anyway, in a manner of speaking.