C函数名称或函数指针? [英] C function name or function pointer?
本文介绍了C函数名称或函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们看一下这段代码:
Let's see this code:
#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;
有效.
When setting world
variable, both
world = f;
and world = &f;
works.
我应该使用哪个?它取决于编译器还是C版本?
Which should I use? Does it depend on the compiler or C version?
% 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
作为参数传递时.
Both world = f;
and world = &f;
works because there is no difference between f
and &f
when passing it as an argument.
请参见 C99 规范(第6.7节).5.3.8).
See C99 specification (section 6.7.5.3.8).
将参数声明为函数返回类型"声明调整为指向函数返回类型的指针",如6.3.2.1.所示.
A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.
这篇关于C函数名称或函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文