C function name or function pointer?

Take a look at 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 the world variable, both world = f; and world = &f; works.

What should i use? Does it depend on the compiler or version of 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 
+6
source share
2 answers

Both world = f; and world = &f; work because there is no difference between f and &f when passed as an argument.

See C99 (section 6.7.5.3.8).

Declaring a parameter as a function return type 'should be adjusted to a' pointer to the function return type, as in 6.3.2.1.

+2
source

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

What should i use?

Thus, for all practical purposes, the name of the function f and the pointer to the same function &f interchangeable. Also see Why do all of these function pointer definitions all work?

Does it depend on the compiler or version of C?

Independent of any compiler or version C.

+1
source

All Articles