Reputation: 73
I encountered two different codes using function pointers.
Please tell me which one is better? Is there any preference?
typedef int myFunction(int a,int b);
extern myFunction *ptfunction;
and
typedef int (*ptfunction)(int a,int b);
Upvotes: 1
Views: 327
Reputation: 49251
Neither, use std::function
std::function<int (int ,int)> ptfunction;
ptfunction = f1;
Example (it's in std in c++0x):
Upvotes: 1
Reputation: 254471
The second is invalid; it would be equivalent to the first if you fix the first line to declare a variable, not a type:
int (*ptfunction)(int a, int b);
Which is "better" depends entirely on what you want to do with these things. If you need to refer to the same type many times, then the typedef
will make things clearer; if you simply want to declare a single function pointer as in your examples, then it just adds extra noise.
(Presumably, in your first example, the second parameter should be int
not int*
, otherwise the function call wouldn't compile).
It's often more convenient and flexible to use function objects, and std::function
in particular, since these can have arbitrary state bound to them. But that's beyond the scope of this question.
Upvotes: 1
Reputation: 1105
for the 1st code, you have to define ptfunction somewhere. and i don't think 2nd code can be compiled.
try this:
typedef int *PTFUNCTION(int, int);
PTFUNCTION func = f1;
func(1, 2);
Upvotes: 0
Reputation: 6200
The first one contains another error: You cannot cast int to a pointer to int. And which one is better? They are both completely out of context.
Upvotes: 0
Reputation: 399863
Both are bad, in that they are syntactically incorrect.
You need:
typedef int (*myFunction)(int a, int *b);
Upvotes: 5