Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do both of these function pointer calling syntax variations work?

Tags:

c

I'm relatively new to C, and found it intriguing that both of the following calls to the function pointer compile and work fine. One with and one without dereferencing the function pointer before calling it.

#include <stdio.h>
#include <stdlib.h>

void func() {
    puts("I'm a func");
}
int main(void) {
    void (*f)() = func;
    f();
    (*f)();
    return EXIT_SUCCESS;
}

I think I understand that (*f)() is the "official" way to call a function pointer, but why does simply calling f() work? Is that syntactic sugar of recent C versions?

like image 412
Eran Medan Avatar asked Jan 23 '14 18:01

Eran Medan


1 Answers

This is a piece of syntactic/semantic sugar that has, AFAIK, worked since the very earliest versions of C. It makes sense if you think of functions as pointers to code.

The only special rule needed to make function pointers work this way is that indirecting a function pointer gives the same pointer back (because you can't manipulate code in standard C anyway): when f is a function pointer, then f == (*f) == (**f), etc.

(Aside: watch out with declaration such as void (*f)(). An empty argument list denotes an old-style, pre-C89 function declaration that matches on the return type only. Prefer void (*f)(void) for type safety.)

like image 85
Fred Foo Avatar answered Oct 27 '22 11:10

Fred Foo