函数返回函数指针

#include <stdio.h>

char *ops[3] = { "sum", "sub", "mul" };

int sum(int a, int b)
{
        return a + b;
}

int sub(int a, int b)
{
        return a - b;
}

int mul(int a, int b)
{
        return a * b;
}

void show(int opnum)
{
        printf("Do the operation:%s\n", ops[opnum]);
}

int (*operation(int opnum, void (*fun) (int))) (int, int)
{
        fun(opnum);
        switch (opnum) {
        case 0:
                return sum;
                break;
        case 1:
                return sub;
                break;
        case 2:
                return mul;
                break;
        default:
                break;
        }

}

int main(int argc, char *argv[])
{
        int a = 33;
        int b = 17;
        printf("Here a=%d, b=%d\n", a, b);
        printf("\tThe result is :%d\n", operation(0, show) (a, b));
        printf("\tThe result is :%d\n", operation(1, show) (a, b));
        printf("\tThe result is :%d\n", operation(2, show) (a, b));
        
        return 0;
}
 

你可能感兴趣的:(函数指针)