#include <stdio.h>
typedef void (*cfp_t)(int a);
cfp_t calls_table[3]={NULL,};
void test(int a)
{
printf("test();\n");
}
int main(void)
{
printf("************0**********\n");
printf("test:%d\n",test);
printf("&test:%d\n",&test);
printf("*test:%d\n",*test);
printf("************1**********\n");
calls_table[0]=test;
calls_table[0](5);
printf("main();\n");
printf("************2**********\n");
calls_table[0]=&test;
calls_table[0](5);
printf("main();\n");
printf("************3**********\n");
calls_table[0]=*test;
calls_table[0](5);
printf("main();\n");
printf("************4**********\n");
calls_table[0]=test;
(*calls_table[0])(5);
printf("main();\n");
printf("************5**********\n");
calls_table[0]=&test;
(*calls_table[0])(5);//执行
printf("main();\n");
printf("************6**********\n");
(&test)(5);
printf("************7**********\n");
(*test)(5);
}
输出结果:
************0**********
test:4195709
&test:4195709
*test:4195709
************1**********
test();
main();
************2**********
test();
main();
************3**********
test();
main();
************4**********
test();
main();
************5**********
test();
main();
************6**********
test();
************7**********
test();
/usercode/file.cpp: In function ‘int main()’:
/usercode/file.cpp:16:30: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘void (*)(int)’ [-Wformat=]
printf("test:%d\n",test);
^
/usercode/file.cpp:17:32: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘void (*)(int)’ [-Wformat=]
printf("&test:%d\n",&test);
^
/usercode/file.cpp:18:32: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘void (*)(int)’ [-Wformat=]
printf("*test:%d\n",*test);
^
由输出结果:可知,函数名,函数名取地址,函数名取值之间可以随意替换。不像数组名,数组名取地址,数组名取值那样区别很大。