Abstract function pointers

How to create an array of ten function pointers? I have a for loop, and I want to set a pointer to another function at each iteration. So:

//pseudocode for i (0..10) function = array_of_functions[i]; //... 
+4
source share
5 answers
 // Define alias for function pointer type for convenience typedef void (*action)(int); // Example function void print(int) { ... } action fs[10] = { print, ... }; for (int i = 0; i < 10; ++i) { action f = fs[i]; // Call it somehow f(i * i); } 
+8
source

This code:

 return_t (*array_of_functions[10])(arg1_t, arg2_t); 

Declares "array_of_functions" as a 10-element array of function pointers, where each directional function takes two arguments of type arg1_t and arg2_t and returns type return_t. Replace the types and adjust the number of arguments as necessary.

+4
source

The easiest way to do this is to create a typedef for your function and then declare an array with that type. To create a typedef for a function: typedef returntype (*typedefname)(argtype1,argtype2,...,argtypeN); EX:

 #include <stdio.h> #include <stdlib.h> typedef void (*functype)(); void func1() { //... } void func2() { //.. } //... void func10() { //... } int main(int argc, char* argv[]) { functype array[] = { &func1, &func2, &func3, &func4, &func5, &func6, &func7, &func8, &func9, &func10 }; // Use the array... return 0; } 
+2
source

Anytime you have to deal with the ugly function pointer syntax, it is best to use typedef.

 #include <iostream> void a(int i) { std::cout<<"a: "<<i<<std::endl; } void b(int i) { std::cout<<"b: "<<i<<std::endl; } typedef void (*fn)(int); int main(int argc, char**argv) { fn foo[2]; foo[0] = a; foo[1] = b; for(size_t i = 0; i < sizeof(foo) / sizeof(foo[0]); ++i) { foo[i](i); } return 0; } 
+2
source
 T (*array_of_functions[10])(); 

Where T is the return type of each function (all functions return the same type, naturally). Everything becomes complicated if you want to store function pointers with different parameter numbers / types:

 int foo(void) {...} int bar(int x) {...} int bletch(double y, double z) {...} ... int (*array_of_functions[10])() = {foo, bar, bletch, ...}; 

If so, you will need to keep track of how many and types of parameters each function requires so that you can correctly name it.

In fact, I am typing typedefs for types of function pointers; they tend to obscure as much as they simplify.

+1
source

All Articles