This question already has answers here:
In C, what is the difference between `&function` and `function` when passed as arguments?

(4个答案)


4年前关闭。




让我们看一下这段代码:
#include <stdio.h>

typedef int (*callback) (void *arg);
callback world = NULL;

int f(void *_) {
    printf("World!");
    return 0;
}

int main() {
    printf("Hello, ");
    // world = f;
    world = &f; // both works
    if (world != NULL) {
        world(NULL);
    }
}

设置world变量时,两者world = f;world = &f;有效。

我应该使用哪个?它取决于编译器还是C版本?
% gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.38)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

最佳答案

world = f;world = &f;都可以使用,因为f&f在作为参数传递时没有区别。

参见C99规范(第6.7.5.3.8节)。

关于C函数名称或函数指针?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39806309/

10-11 15:32
查看更多