简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM