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
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.
Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures.
Function pointers in C are variables that can store the memory address of functions and can be used in a program to create a function call to functions pointed by them.
Function pointers can be stored in variables, structs, unions, and arrays and passed to and from functions just like any other pointer type. They can also be called: a variable of type function pointer can be used in place of a function name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With