Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function name or function pointer? [duplicate]

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
like image 237
mash Avatar asked Oct 01 '16 11:10

mash


People also ask

Is function name a pointer in C?

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.

Can two functions have the same name in C?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures.

What is function Pointers in C?

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.

Can we declare function pointer in structure?

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.


1 Answers

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.

like image 175
imadhsissou Avatar answered Sep 30 '22 11:09

imadhsissou