Array of functions?

Is it actually possible to create an array of functions. I've looked around and tried different methods but none of them seem to work.
Stuff like: fn[0]();

Is it actually possible is what I want to know or do I need to learn DLL's.
I don't think you can create an array of functions...you might be able to create an array of pointers to functions, although I don't really know how you would go about doing that or if it would even work the way I am thinking it would.
Yeah, you totally can. Haven't compiled this, but it should work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

typedef int (*IntFunctionWithOneParameter) (int a);

int function(int a){ return a; }
int functionTimesTwo(int a){ return a*2; }
int functionDivideByTwo(int a){ return a/2; }

void main()
{
    IntFunctionWithOneParameter functions[] = 
    {
        function, 
        functionTimesTwo, 
        functionDivideByTwo
    };

    for(int i = 0; i < 3; ++i)
    {
        cout << functions[i](8) << endl;
    }
}


edit: compiled. it works like you think it should.
Last edited on
Thanks, great solution. Saves alotta time and trouble. I think I'll look into that typedef; you can define anything I presume...
But Cheif haven't you just confirmed firedraco point??

You haven't created an array of functions - you have created an array of function pointers.. :-)
Its plausible as long as it works, its true they are pointers but I wasn't specifically looking out for function arrays as such, just a way to store a bunch of them together.
Topic archived. No new replies allowed.