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);
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);
Both are bad, in that they are syntactically incorrect.
You need:
typedef int (*myFunction)(int a, int *b);
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.
Neither, use std::function
std::function<int (int ,int)> ptfunction;
ptfunction = f1;
Example (it's in std in c++0x):
std:::function instead, but there's no need for std::bind in there at all. You can just do ptfunction = f1;