首页 > 代码库 > 9.02 函数指针的数组简明用法

9.02 函数指针的数组简明用法

#include <stdio.h>

int sum(int,int);
int product(int,int);
int different(int,int);

int main(void)
{
    int a = 10;
    int b = 5 ;
    int result = 0;
    int (*pfun[3])(int,int);
    
    //其实也可以这样用,int (*pfun[3])(int,int) = {sum,product,different};
    pfun[0] = sum;
    pfun[1] = product ;
    pfun[2] = different ;

    for(size_t i = 0;i<3;i++)
    {
        result = pfun[i](a,b);
        printf("result = %2d\n",result);
    }

    result = pfun[1](pfun[0](a,b),pfun[2](a,b));
    printf("混合结果为 %2d\n",result);
    return 0;
}

int sum(int x,int y)
{
    return x+y;
}

int product(int x,int y)
{
    return x*y;
}

int different(int x,int y)
{
    return x-y;
}

 

9.02 函数指针的数组简明用法