I was recently reading a code, and found that a function pointer is written as :
int (*fn_pointer ( this_args ))( this_args )
I usually encounter a function pointer like this :
return_type (*fn_pointer ) (arguments);
Similar thing is discussed here:
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
Can somebody tell me what is the difference and how does this work ?
From cdecl (which is a handy helper tool to decipher C declarations):
Hence the former is a function, that returns pointer to function, while the latter:
return_type (*fn_pointer ) (arguments);
is an ordinary "pointer to function".
Read more about undestanding complex declarations from the Clockwise/Spiral Rule article.
declares
fn_pointer
as a function that takesthis_args
and returns a pointer to a function that takesthis_args
as argument and returns anint
type. It is equivalent toLet's understand it a bit more:
How to read
int (*f4(arg3))(arg1, arg2);
So, finally a home work :). Try to figure out the declaration
and use
typedef
to redefine it.This
declares a function that takes as arguments
this_args1
and returns a function pointer of typeso it's just a function that returns a function pointer.