C语言函数指针与调用

C语言函数指针与调用

平时我们使用函数传递的参数一般为数据变量,那么是否可以传递函数呢?
答案是不但可以,而且习惯以后,会用上瘾的。通过传递不同的函数指针,我们可以实现在函数中调用不同的子函数。
下面就举个栗子,说一下函数指针的用法。
有四个函数:
int add2(int a, int b)
{
return a+b;
}

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

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

int div2(int a, int b)
{
return a/b;
}
下面将演示如何天下一统,通过一个函数实现对两个输入形参的不同运算!
定义一个函数:
int calculate(int a, int b, int (*fun_t)(int a, int b))
{
int result;
result = fun_t(a, b); // 运算
result++;
return result;
}
形参 int (*fun_t)(int a, int b),int表示返回值类型,也可写成
int calculate(int a, int b, int *fun_t(int a, int b))。
在main中使用此函数:
void main(void)
{
int result1,result2;
int a = 192, b = 48;

/* 两个数相加的操作 */
result1 = calculate(a, b, add2);
result2 = calculate(a, b, mul2);
}
仿真跟踪,进入第一次调用,形参fun_t值为0x410C,即add2函数地址。
仿真运行add2函数
感觉形参int *fun_t(int a, int b)太繁琐?
我们可以这样定义函数:
int calculate(int a, int b, int *fun_t(int , int ))
{
int result;
result = fun_t(a, b); // 运算

return result;
}
还嫌麻烦?有办法,别忘了typedef!
typedef int *fun_t(int, int);
int calculate(int a, int b, fun_t operation)
{
int result;
result = operation(a, b); // 运算
return result;
}

编译仿真,运行结果相同。
仿真运行mul2函数

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值