Reputation: 67376
Everytime I look at a C function pointer, my eyes glaze over. I can't read them.
From here, here are 2 examples of function pointer TYPEDEFS:
typedef int (*AddFunc)(int,int);
typedef void (*FunctionFunc)();
Now I'm used to something like:
typedef vector<int> VectorOfInts ;
Which I read as
typedef vector<int> /* as */ VectorOfInts ;
But I can't read the above 2 typedefs. The bracketing and the asterisk placement, it's just not logical.
Why is the * beside the word AddFunc..?
Upvotes: 3
Views: 3659
Reputation: 224199
I read
typedef vector<int> /* as */ VectorOfInts ;
It's probably better if you see a typedef
as an object definition with a typedef
put in front:
int i;
defines an integer object
typedef int t;
defines an integer type.
vector<int> v;
defines a vector object
typedef vector<int> v;
defines a vector type.
int (*AddFunc)(int,int)
defines a function pointer
typedef int (*AddFunc)(int,int)
defines a function pointer type.
C's declaration syntax, inherited by C++, is a mess. I agree that typedef int (*)(int,int) AddFunc;
would make more sense. But C's declaration syntax is 40 years old, has never changed, and never will. You'd better get used to it.
Upvotes: 3
Reputation: 229934
Function declarations look like this:
int AddFunc(int,int);
void FunctionFunc();
A typedef defining a function type looks the same, just with typedef
in front:
typedef int AddFunc_t(int,int);
typedef void FunctionFunc_t();
To define a pointer to such a function type, there needs to be an additional *
with additional parenthesis to specify where that *
belongs to:
typedef int (*pAddFunc_t)(int,int);
typedef void (*pFunctionFunc_t)();
(The *
is always right before the typename/variable that gets defined as a pointer.)
To read such a function pointer proceed in the opposite direction: leave out the (* ... )
around the type name and the typedef
in front. The result then looks like a normal function declaration of the relevant type.
Upvotes: 2
Reputation: 355367
The actual type of the first one is
int (*)(int,int);
(that is, a pointer to a function that takes two parameters of type int
and returns an int
)
The *
identifies it as a function pointer. AddFunc
is the name of the typedef.
cdecl can help with identifying particularly complex type or variable declarations.
Upvotes: 4
Reputation: 258578
When you're comprehending it, just ignore the typedef
, the parentheses around the function name, and the asterisk in front of the name. Then you have int AddFunc(int,int);
.
The point of the parentheses in (*functionName)
is to specifically group the *
with the name of the typedef. The *
is necessary to indicate that this is a function pointer.
So any function that takes two int
s as arguments and returns an int
complies to the AddFunc
"interface", if you will. Likewise, any function accepting no arguments are returning void can be used for a FunctionFunc
.
Upvotes: 5