Search code examples
arrayscargumentsfunction-pointers

How to pass an array of function pointers as an argument?


I have an array of function pointers int (*oper_ptr[4])(int, int) = {add, sub, mul, divi}; for the below functions which simply perform a standard operation on two passed integers:

int add(int num_a, int num_b); 
int sub(int num_a, int num_b); 
int mul(int num_a, int num_b); 
int divi(int num_a, int num_b); 

What is the best way to pass this array into another function. I have tried: void polish(char* filename, int (*oper_ptr[4])(int, int)) with for e.g., oper_ptr[0](num_a, num_b); to call the first function.


Solution

  • The way you have done it works. But as always with function pointers, it's a bad idea to use them without typedef:

    typedef int operation (int num_a, int num_b); 
    
    void polish (char* filename, operation* op[4]);