如何在c中使用带参数的函数指针?

Son*_*ami 3 c syntax function-pointers

你如何使用这个函数指针声明?

int (* get_function(char c)) (int, int);
Run Code Online (Sandbox Code Playgroud)

我有三个功能int function_a(int a, int b)int function_b(int a, int b)int function_c(int a, int b)。我想使用上面的函数指针基于c.

mch*_*mch 6

下面是一个例子:

#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;
}
Run Code Online (Sandbox Code Playgroud)

get_function('B')返回一个指向function_bget_function('B')(3, 5);调用该函数的函数指针。

https://ideone.com/0kUp47