bri*_*ice 20 c functional-programming function operators
例如:
#include <stdio.h>
typedef void (* proto_1)();
typedef void proto_2();
void my_function(int j){
printf("hello from function. I got %d.\n",j);
}
void call_arg_1(proto_1 arg){
arg(5);
}
void call_arg_2(proto_2 arg){
arg(5);
}
void main(){
call_arg_1(&my_function);
call_arg_1(my_function);
call_arg_2(&my_function);
call_arg_2(my_function);
}
Run Code Online (Sandbox Code Playgroud)
运行这个我得到以下内容:
> tcc -run try.c
hello from function. I got 5.
hello from function. I got 5.
hello from function. I got 5.
hello from function. I got 5.
Run Code Online (Sandbox Code Playgroud)
我的两个问题是:
(* proto)和没有定义的函数原型有什么区别?&)调用函数和不调用函数有什么区别?作为争论时,&function和之间没有区别function
但是你的typedef之间有区别.我不知道官方的解释,即究竟是什么区别,但我记得
typedef void (*name1)(void);
Run Code Online (Sandbox Code Playgroud)
和
typedef void(name2)(void);
Run Code Online (Sandbox Code Playgroud)
是不同的:
name1是一个指向函数的指针,该函数不带参数,也不返回任何参数
name2是一个不带参数的函数,不返回任何内容
你可以通过编译测试它:
typedef void (*pointer)(void);
typedef void (function)(void);
void foo(void){}
int main()
{
pointer p;
function f;
p = foo; //compiles
p();
f = foo; //does not compile
f();
}
Run Code Online (Sandbox Code Playgroud)
再次,我不是解释这种行为的确切原因的合适人选,但我相信如果你看看标准,你会发现那里的解释
&function和function之间没有区别 - 它们都是地址.您可以通过打印它们来看到这一点:
function bar();
....
printf("addr bar is 0x%d\n", &bar);
printf("bar is 0x%d\n", bar);
Run Code Online (Sandbox Code Playgroud)