2016-10-01 109 views
6

让我们来看看下面的代码:C函数名称或函数指针?

#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 
+4

http://stackoverflow.com/questions/6293403/in-c-what-is-the-difference-between-function-and-function-when-passed-as-a – Pavel

+0

http:// stackoverflow .COM /问题/ 3674200 /什么,做-A-的typedef与 - 括号样的typedef INT-fvoid均值 - 是 - 它-A –

回答

2

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

参见C99规范(第6.7.5.3.8节)。

参数声明为“函数返回类型”应调整为“指向函数返回类型的指针”,如6.3.2.1所示。

1

你的功能fint (void *_)类型。每当在表达式中使用f时,它都会隐式转换为指向自身的指针,该指针的类型为int(*) (void *_)

我应该使用哪一个?

因此,出于所有实际目的,函数f的名称和指向相同函数&f的指针是可互换的。也看看"Why do all these function pointer definitions all work? "

它取决于编译器或C版本吗?

不依赖于任何的编译器或C版本。