3

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.

1
  • 3
    int (* get_function(char c)) (int, int); is not a function pointer, it is a function, getting a char c and returning a pointer to a function. Commented May 29, 2020 at 13:53

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.