(编程基础)函数指针

函数指针,简而言之就是指向函数的指针,引用wiki上的标准解释如下:

A function pointer (or subroutine pointer or procedure pointer) is a type of pointer supported by third-generation programming languages (such as PL/I, COBOL, Fortran,[1] dBASE dBL, and C) and object-oriented programming languages (such as C++ and D).[2] Instead of referring to data values, a function pointer points to executable code within memory. When dereferenced, a function pointer can be used to invoke the function it points to and pass it arguments just like a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked indirectly through a variable instead of directly through a fixed name or address. Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values.

大意就是:函数指针指向内存上一段可执行代码的入口地址,而不是具体的数值,当解引用的时候,函数指针可以用来调用他所指向的函数,传值给这个函数,就像正常的函数调用一样,函数被指针变量间接的调用而不是直接使用固定的函数名和地址,这个调用就是我们所熟知的“间接调用”,在运行态的时候,函数指针通过提供一种简单的办法来选择具体执行哪个函数,以此达到简化代码的目的(小弟的渣渣英语,各位将就看看就行)。


先来了解一下函数指针的最基本用法,指向函数的指针:

#include <stdio.h>

void hello(const char *str)
{
	printf("%s\n", str);
}

int main()
{
	const char *str = "hello world";
	void (*cb)(const char*);
	cb = hello;
	cb(str);
	return 0;
}

定义了一个函数指针,名字叫做cb,返回值为void,参数是const char*,然后定义了一个函数原型hello,返回值为void,参数是const char*,大家应该看出来了一点东西,函数指针cb跟函数原型hello的一些信息是匹配的,这样子也就是说函数指针cb可以正确的指向函数原型hello,测试用例里面就是用函数原型hello来初始化函数指针cb的(由于函数名就是函数的入口地址,因此这里也可以看作函数指针cb指向了hello的函数入口),因此后续调用cb就是直接调用hello了,这印证了wiki里面的一句话:“a function pointer can be used to invoke the function it points to and pass it arguments just like a normal function call”

这里需要注意两点:

1:定义函数指针,明确返回值和参数,如果跟函数原型的返回值和参数有冲突可是有问题的哈。

2:用函数原型来初始化函数指针,这样子函数指针就跟函数原型之间的关系建立起来了,后面就可以直接用函数指针来call函数原型了。



函数指针的最重要用法非callback莫属了,一个简单的callback例子如下:

#include <stdio.h>

void my_name(const char *name)
{
	printf("my name is %s\n", name);
}

void your_name(const char *name)
{
	printf("your name is %s\n", name);
}

void call_back(void (*callback)(const char*), const char *name)
{
	callback(name);
}

int main()
{
	const char *name = "cheny";
	call_back(my_name, name);
	call_back(your_name, name);
	return 0;
}

运行结果如下:

cheny@cheny-laptop:~$ ./a.out
my name is cheny
your name is cheny


我们定义了一个函数call_back,函数的第一个参数是一个函数指针callback,然后定义了两个函数原型,他们的返回值和参数跟函数指针是匹配的哈(这样子可以保证函数指针跟函数原型可以成功搞基~),然后在调用函数call_back的时候,传进去的第一个参数可以是上述的两个函数原型里面的任意一个,这样子就可以把函数当作参数一样传递,这也就实现了callback,从运行结果可以看出,call_back函数具体的打印取决与函数的第一个参数,这印证了wiki里面的另一句话:“Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values.”

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值