引入
// 加法函数
int add(int a, int b){
return a+b;
}
// 函数指针
int (*Add)(int a, int b);
// 使用方式
int main(){
Add = add;
}
函数指针用的比较少,从上面的代码中可以感性的了解到函数指针和函数声明很相似,不同的是函数指针的名字外面需要用括号括起来。
__attribute__机制
在函数前加上__attribute__
可以设置函数的属性,其中一种用法是强制让函数在main执行之前执行,即使main中没有调用该函数,例如:
__attribute__((constructor))
void test(){
printf("hello function test\n");
}
int main(){
printf("Hello function main\n");
return 0;
}
注意需要在__attribute__
后面需要加上constructor
,在main中没有调用test函数,但是在程序执行时,会先执行test函数,再执行main函数。
注册函数
python中有一个用法是import A as B
,就相当于用B这个函数名来调用函数A,当A的名字比较长时,常用B来作为A的简称。在C中这一功能可以用上面提到的函数指针和__attribute__
来完成,当需要对多个函数改名时,则可以用注册函数来完成,代码如下:
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
// 用于实现注册函数
void test1(){
printf("hello function test1\n");
}
void test2(){
printf("hello function test2\n");
}
void test3(){
printf("hello function test3\n");
}
void test4(){
printf("hello function test4\n");
}
// 函数指针数组
void (*func[4])();
// 注册函数
__attribute__((constructor))
void regFunction(){
func[1] = test1;
func[2] = test2;
func[3] = test3;
func[4] = test4;
}
int main(){
srand(time(0));
int select = rand()%3;
func[select]();
}
注意到注册函数是在main函数之前强制执行的,之后就可以用func[i]
来代替testi
了,这是极为方便的,我记得python中也有这样的用法, 用一个数组来存放多个函数名,依据不同的情况分别调用这些函数,这种用法似乎能减少分支语句。