Search code examples
csyntaxfunction-pointers

How can you use a function pointer with argument in c?


How can you use this function pointer declaration?

int (* get_function(char c)) (int, int);

I have three functions int function_a(int a, int b), int function_b(int a, int b) and int function_c(int a, int b). I want to use the above function pointer to call one of my functions conditionally based on c.


Solution

  • Here is an example:

    #include <stdio.h>
    
    int function_a(int a, int b)
    {
        printf("Inside function_a: %d %d\n", a, b);
        return a+b;
    }
    
    int function_b(int a, int b)
    {
        printf("Inside function_b: %d %d\n", a, b);
        return a+b;
    }
    
    int function_c(int a, int b)
    {
        printf("Inside function_c: %d %d\n", a, b);
        return a+b;
    }
    
    int function_whatever(int a, int b)
    {
        printf("Inside function_whatever: %d %d\n", a, b);
        return a+b;
    }
    
    
    int (* get_function(char c)) (int, int)
    {
        switch(c)
        {
            case 'A':
                return function_a;
            case 'B':
                return function_b;
            case 'C':
                return function_c;
        }
        return function_whatever;
    }
    
    int main(void) {
        get_function('B')(3, 5);
        return 0;
    }
    

    get_function('B') returns a function pointer to function_b and get_function('B')(3, 5); also calls that function.

    https://ideone.com/0kUp47