C函数名还是函数指针?
C function name or function pointer?
让我们看看这段代码:
#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
您的函数 f
的类型为 int (void *_)
。每当在表达式中使用 f
时,它都会隐式转换为指向自身的指针,类型为 int(*) (void *_)
.
Which should I use?
因此,对于所有实用目的,函数名 f
和指向同一函数的指针 &f
是可以互换的。也看看 "Why do all these function pointer definitions all work? "
Does it depend on the compiler or C version?
不依赖于任何编译器或 C 版本。
world = f;
和 world = &f;
都有效,因为 f
和 &f
在将其作为参数传递时没有区别。
参见 C99 规范(第 6.7.5.3.8 节)。
A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.
让我们看看这段代码:
#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
您的函数 f
的类型为 int (void *_)
。每当在表达式中使用 f
时,它都会隐式转换为指向自身的指针,类型为 int(*) (void *_)
.
Which should I use?
因此,对于所有实用目的,函数名 f
和指向同一函数的指针 &f
是可以互换的。也看看 "Why do all these function pointer definitions all work? "
Does it depend on the compiler or C version?
不依赖于任何编译器或 C 版本。
world = f;
和 world = &f;
都有效,因为 f
和 &f
在将其作为参数传递时没有区别。
参见 C99 规范(第 6.7.5.3.8 节)。
A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.