1

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);
3
  • I'd go with the first seeing as the second won't compile. Commented Jul 4, 2012 at 14:38
  • I don't really understand the need of typedef here. Wouldn't simply declaring int (*ptfunction)(int a,int b); achieve the same as the typedef? And I consider the simple declaration to be more clear. (And in case you don't need it, the compiler will optimize it away anyways...) Commented Jul 4, 2012 at 14:39
  • It would be helpful if you edited your original post and added two working examples. Commented Jul 4, 2012 at 14:42

5 Answers 5

5

Both are bad, in that they are syntactically incorrect.

You need:

typedef int (*myFunction)(int a, int *b);
Sign up to request clarification or add additional context in comments.

1 Comment

The first is fine (syntactically at least) - you can define a function type, you just can't declare objects of that type.
1

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.

Comments

1

Neither, use std::function

std::function<int (int ,int)> ptfunction;
ptfunction = f1;

Example (it's in std in c++0x):

how to use boost bind

std::function

3 Comments

I like the suggestion of using std:::function instead, but there's no need for std::bind in there at all. You can just do ptfunction = f1;
Well i wasn't really sure you could do that without the bind.
You only need bind if you want to do more complex things rather than just forward.
0

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.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.