cfunction-pointersreturn-typefunction-declaration

Understanding Function Definitions that Return a Function Pointer


I am hoping to get some help with understanding why function definitions, with function pointer return types need to be written the following way.

int ( * functionFactory (int n) ) (int, int) { Function Body }

function definition taken from How do function pointers in C work?

This is what I imagine each part means.

returned function's | function  Returns  |                  | called function's | returned function's
return type         | a function pointer | name of function | arguments         | arguments 
  |                   |                          |                  |                   |
 _V_                 _V_     ____________________V________   _______V_                 _V______
|   |               |   |   |                             | |         |               |        |
 int               (  *             functionFactory           (int n)  )              (int, int) { Function Body }

But why is it not written more like a normal function with the return type all together at the start like this.

return type       name of function  arguments
      |                 |             |
 _____V_________   _____V_______   ___V_
|               | |             | |     |
int (*)(int, int) functionFactory (int n) { Function Body }

Solution

  • This is an artifact of the C syntax principle “declaration mirrors use”.

    Given a declaration int ( * functionFactory (int n) ) (int, int), one way you could use it would be

    int result = (*functionFactory(42))(123, 456);
    

    in order to call the factory with the argument 42, then immediately invoking the resulting pointer with 123, 456.

    Now, it’s generally bad practice to actually use such a declaration in real life as it would be widely considered unreadable. Instead, the usual advice is to use a typedef:

    typedef int (*fptr_t)(int, int);
    fptr_t functionFactory(int n) { … }