Array Of Functions

I would like to know if their is a way to make an array of functions.
like this

array[] = {function1, function2, function 3}
function1;
would there be a way, or is it even possible?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//function pointer typedef:
typedef void (*f_t)();

void f1(){
    std::cout <<"f1()\n";
}

void f2(){
    std::cout <<"f2()\n";
}

void f3(){
    std::cout <<"f3()\n";
}

int main(){
    f_t array[]={ f1, f2, f3 };
    for (int a=0;a<3;a++)
        array[a]();
}
Last edited on
Is that the only way, oh well, i guess that'll work.

it won't compile correctly.
Last edited on
On an unrelated note, why do some people capitalize every word like that?

This isn't the first time I've seen it, and every time I see it, I'm baffled. It's goofy looking, and must be very unnatural to type.
you know i dont know i get it from when i used to be a video game modder.
i used to capital the letters like that when i'd print stuff out on the screen or else it'd look weird.
helios' way compiled and ran fine for me.

If you have a compiler that supports the new C++ standard (C++11) then you can use the std::function class. Here is an example using std::function and std::vector instead of function pointers and arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

#include <vector>
#include <functional>

void f1(){
    std::cout <<"f1()\n";
}

void f2(){
    std::cout <<"f2()\n";
}

void f3(){
    std::cout <<"f3()\n";
}

int main()
{
	std::vector<std::function<void()> > funcs;

	funcs.push_back(f1);
	funcs.push_back(f2);
	funcs.push_back(f3);

	for(size_t f = 0; f < funcs.size(); ++f)
		funcs[f]();

	return 0;
}
f1()
f2()
f3()
Last edited on
closed account (zb0S216C)
Here's how to declare an array of function pointers:

1
2
3
4
5
6
7
8
9
10
11
int Function( int Arg )
{
    // ...
}

int( *Ptr[3] )( int );

Ptr[0] = &Function;

// Call the function:
Ptr[0]( 10 );


Wazzak
Last edited on
Topic archived. No new replies allowed.