Read Function Pointer Syntax
Every time I look at the C function pointer, my eyes look back. I cannot read them.
From here , here are 2 examples of a TYPEDEFS function pointer:
typedef int (*AddFunc)(int,int);
typedef void (*FunctionFunc)();
Now I am used to something like:
typedef vector<int> VectorOfInts ;
What i read as
typedef vector<int> /* as */ VectorOfInts ;
But I cannot read the above 2 typedefs. Bracketing and sprocket placement is just illogical.
Why * besides the word AddFunc ..?
a source to share
The actual type of the first
int (*)(int,int);
(i.e. a pointer to a function that takes two type parameters int
and returns int
)
*
identifies it as a function pointer. AddFunc
is the name of the typedef.
cdecl can help you define particularly complex type or variable declarations.
a source to share
When you understand it, just ignore the typedef
parentheses around the function name and the asterisk in front of the name. Then there you have it int AddFunc(int,int);
.
The point of parentheses in (*functionName)
is a specific grouping *
named typedef. *
it is necessary to indicate that this is a function pointer.
Therefore, any function that takes two int
as arguments and returns int
conforms to the AddFunc
" interface " if you do so. Likewise, any function that takes no arguments returns void, which can be used for FunctionFunc
.
a source to share
I read
typedef vector<int> /* as */ VectorOfInts ;
It is probably better if you see typedef
how defining an object using typedef
at the beginning :
-
int i;
defines an integer objecttypedef int t;
defines an integer type . -
vector<int> v;
defines a vector objecttypedef vector<int> v;
defines a vector type . -
int (*AddFunc)(int,int)
defines a function pointertypedef int (*AddFunc)(int,int)
defines a function pointer type .
The C declaration syntax inherited from C ++ is a mess. I agree that typedef int (*)(int,int) AddFunc;
would make more sense. But the C declaration syntax is 40 years old, has never changed, and never will. You better get used to it.
a source to share
Function declarations look like this:
int AddFunc(int,int);
void FunctionFunc();
The typedef that defines the type of the function looks the same, only with the typedef
front:
typedef int AddFunc_t(int,int);
typedef void FunctionFunc_t();
To define a pointer to this type of function, you must specify an additional one *
with an extra parenthesis to indicate what it belongs to *
:
typedef int (*pAddFunc_t)(int,int);
typedef void (*pFunctionFunc_t)();
( *
always to the right before the name / variable that is defined as a pointer.)
To read such a function pointer, proceed in the opposite direction: leave (* ... )
around the type name and typedef
in front. The result then looks like a declaration of a normal function of the appropriate type.
a source to share