Returning a pointer to a function in C syntax -


in 1 of answer how function pointers in c work? 1 user explains how use function pointers in return values. here's code in question:

// function called functionfactory receives parameter n // , returns pointer function receives 2 ints // , returns int  int (*functionfactory(int n))(int, int) {     printf("got parameter %d", n);     int (*functionptr)(int,int) = &addint;     return functionptr; } 

for me way declare functionfactory function weird - seems me mix return type (pointer function) , function name (functionfactory).

for example, when write simple function returns square of argument write like

int square(int n){     return n*n; } 

clearly, type of return on left , write function name , parameters accepts. when return pointer function why don't write like:

( int (*function)(int, int) ) functionfactory(int n) { ... 

here return type (which pointer function) , details (e.g. function point returns , accepts parameters) on left separated , name of functionfactory function right. me version seems more logical , clear, why don't write that?

this falls out of how declarator syntax works. may think in terms of substitution. here's 1 way it:

t    f   (); // f function returning t      |      v t  (*p)  (); // p pointer function returning t      |      v t  (*q())(); // q function returning pointer function returning t 

so start function declarator f(). replace f pointer (*p), giving declarator (*p)(). replace p function q(), giving declarator (*q())().

edit

you may hear people talk "spiral rule" when reading hairy declarators. while it's more of guideline actual rule, falls out of following precedence rules:

t *a[n];    // array of pointer t t (*a)[n];  // pointer array of t t *f();     // f function returning t t (*f)();   // f pointer function returning t 

the postfix [] , () operators have higher precedence unary *, hence need parentheses when declaring pointers arrays or functions. when read t (*q())();, start leftmost identifier q , "spiral" outwards:

    +-----------+     | +-------+ |     | | +---+ | |              | | |   | | |     t ( * q ()) ()       | | | | | |       | | +-+ | |       | +-----+ |           +---------+ 

breaking down piece piece:

    q        -- q     q()      -- function returning    *q()      -- pointer   (*q())()   -- function returning t (*q())();  -- t 

you cannot declare arrays of function type, nor can declare functions return array types:

t a[n]();    // not allowed  t f()[n];    // not allowed  

so in combination of function , array types, pointer involved, spiral rule holds.


Comments