函数指针

来源:互联网 发布:进销存记账软件 编辑:程序博客网 时间:2024/06/07 20:59
#include <stdio.h>

#include <stdlib.h>


typedef int (*pFunc)(int,int);//typedef给函数指针取别名为pFunc,函数指针为pFunc,pFunc指向一个函数,这个函数的返回值为int型,两个参数都为int型



int add(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;
}


int mdiv(int a, int b)
{
    return a/b;

}


pFunc callback(char opt)
{
    switch(opt)
    {
    case '+':
        return add;
    case '-':
        return sub;
    case '*':
        return mul;
    case '/':
        return mdiv;
    default:
        return NULL;
    }

    return NULL;
}


int calculate(char opt, int a, int b)
{
    pFunc fp = callback(opt);
    return fp(a,b);
}


int main()
{
    int a,b;
    printf("please input two nuber:\n");
    scanf("%d%d",&a,&b);

    printf("%d %c %d = %d\n", a,'+', b, calculate('+', a, b));
    printf("%d %c %d = %d\n", a,'-', b, calculate('-', a, b));
    printf("%d %c %d = %d\n", a,'*', b, calculate('*', a, b));
    printf("%d %c %d = %d\n", a,'/', b, calculate('/', a, b));

    return 0;
}
原创粉丝点击