Tim
Tim

Reputation: 169

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 }

Upvotes: 2

Views: 88

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

This record

int ( * functionFactory (int n) ) (int, int);

can be represented like

int declarator (int, int);

where the declarator is represented like

( * functionFactory (int n) )

That is it is a function that returns a pointer and has one parameter of the type int. And the returned pointer is a pointer to a function of the type int ( int, int ) as it is seen from the shown already record

int declarator (int, int);

. And it was already mentioned in other answers the declaration could be simplified using typedef like for example

typedef int ( *Fp )( int, int );
Fp functionFactory( int );

or

typedef int Func( int, int );
Func * functionFactory( int );

Upvotes: 1

gulpr
gulpr

Reputation: 4608

I would suggest useing function types.

typedef int myfunction(int,int);

myfunction *functionFactory(int n)
{
    /* the code */
}

Upvotes: 1

nneonneo
nneonneo

Reputation: 179677

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) { … }

Upvotes: 5

Related Questions