2

I am trying to understand C function pointers. I made this example to describe what I do not understand about the syntax specifically.

//somewhere in a .h
void(*func_pointer)(int i);

//somewhere in a .c
void func_test(int i)
{
    printf("%d\n", i);
}

//initializing the func_pointer
func_pointer = &func_test;// works as expected
func_pointer = func_test;//why this works ? left: pointer, right: function
func_pointer = *func_test;//why this works ? left: pointer, right: ?

//calling the func
(*func_pointer)(2);//works as expected
func_pointer(2);//why this works ? calling a pointer ?

Why is this syntax accepted ?

dimitris93
  • 4,155
  • 11
  • 50
  • 86
  • Is there a reason not to close this as a duplicate of [How do function pointers in C work?](http://stackoverflow.com/questions/840501/)? The reasons are mainly hysterical…I mean, historical. Although you're mostly querying the newer, more recent, less encrusted notations. – Jonathan Leffler Apr 08 '15 at 01:45
  • @JonathanLeffler I actually had this question opened in another tab as we speak. However in the answer, only `func_pointer = &func_test;` and `(*func_pointer)(2);` was used, which makes complete sense syntax-wise. I am just confused of why the other syntax cases even work at all, because I expected that it should give a compile error – dimitris93 Apr 08 '15 at 01:51
  • 1
    You might also find [Understanding typedefs for function pointers in C](http://stackoverflow.com/questions/1591361/) helpful, too. And I think you should look at [How typedef works for function pointers](http://stackoverflow.com/questions/9357520/how-typedef-works-for-function-pointers/9357637#9357637). – Jonathan Leffler Apr 08 '15 at 01:51
  • 2
    In pre-standard C, the `(*pointer)(args)` notation was necessary for calling a function via a pointer, and the `&` was not used (because a function name is a sort of pointer to function). Then the simpler `pointer(args)` notation was allowed by the standard, probably with some precedent. The `&` didn't do any harm; the `*` I've never understood — look at the second question linked in my previous comment. But the standard says "it shall be like this", so that is how it is. – Jonathan Leffler Apr 08 '15 at 01:54
  • @JonathanLeffler thanks a lot, I will check all of this, looks interesting :) – dimitris93 Apr 08 '15 at 01:56

1 Answers1

2

func_pointer = func_test and func_pointer = *func_test work because function names are automatically turned into function addresses when used in this context. func_pointer(2) works because function pointers automatically dereference themselves, much like references. As to why they do these things, I don't know. Maybe it was decided the syntax was complicated enough already.

MadDoctor5813
  • 281
  • 4
  • 16