C function name or function pointer? [duplicate]

霸气de小男生 提交于 2021-01-22 06:34:08

问题


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);
    }
}

When setting world variable, both world = f; and world = &f; works.

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

回答1:


Both world = f; and world = &f; works because there is no difference between f and &f when passing it as an argument.

See C99 specification (section 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.




回答2:


Your function f is of type int (void *_). Whenever f is used in an expression, it is implicitly converted to a pointer to itself, which is of type int(*) (void *_).

Which should I use?

So, for all practical purposes, the name of a function f and a pointer to the same function &f are interchangeable. Also have a look at "Why do all these function pointer definitions all work? "

Does it depend on the compiler or C version?

Not depend on any compiler or C version.



来源:https://stackoverflow.com/questions/39806309/c-function-name-or-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!