参数列表中的C函数声明

mar*_*mad 5 c c++ function

我在C代码中发现有点令人困惑的事情

struct SomeStruct {
    // ...
    void (*f)(const void *x);
};

void do_some( void f(const void *x) ) { // what?
    struct SomeStruct* v;
    // ...
    v->f = f;
}
Run Code Online (Sandbox Code Playgroud)

我可以理解do_some取函数而不是函数指针.但是void do_some( void (*f)(const void *x) )在实践中有什么不同?什么时候应该用这个?在C++中允许这样做吗?

fre*_*low 7

没有区别.这只是语法糖.它在C和C++中都是允许的.

函数参数简单地由编译器重写为函数指针参数,就像编译器将数组参数重写为指针参数一样.

作为参考,这里是C标准第3.7.1节的摘录:

g(int (*funcp)(void))

// ...

or, equivalently, 

g(int func(void))
Run Code Online (Sandbox Code Playgroud)

  • 只是aq先生,`v-> f = f;`是允许的吗?我的意思是函数返回类型不同,对吗? (2认同)