Re: Function Pointers
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Mon, 21 Jan 2008 22:56:09 +0000
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> writes:
bwaichu@xxxxxxxxx said:
On Jan 21, 11:42 am, Keith Thompson <ks...@xxxxxxx> wrote:
If you feel the need for a generic pointer-to-function type, you
should probably create a typedef for it.
Can you walk me through the typedef'ing of a function pointer? I'm
not clear on the syntax, and the examples posted early confuse me. Is
the purpose of the typedef to make the code more readable?
Others have shown you how to typedef a function pointer type. My own take
is that it's better not to do this, because I don't like hiding pointers
in typedefs.
Ditto. In fact I posted such an example in my reply to the OP! I was
not going to bother saying this except that I find I have two points to
add:
So I would typedef the function type itself:
typedef int myfunctiontype(int, char **);
and then I'd define a pointer to it using a good old out-in-the-open *,
like this:
myfunctiontype *entrypoint = main;
(It's true that myfunctiontype foo; is an error because you can't create
objects of function type, but the answer to that is easy: Don't Do
That.)
You can, however, *declare* functions using it. I have done that once or
twice in code that looked a bit like this:
typedef int op_type(int, int);
extern op_type op_add, op_sub, op_mul, op_div;
op_type *op_table[] = { op_add, op_sub, op_mul, op_div };
It does not buy you much, but it is slightly neater than some alternatives.
I accept that this way may not be everybody's slice of apple pie. Style is
often a matter of taste.
I also prefer to see the "pointerlyness" of pointers, but when it is
hidden I think it matters least with function pointers, simply because
the use makes the type so clear. As soon as you see
op_table[0](a, b);
you know what is going on. There are operations on data pointers that
don't make it obvious that they are pointers (like addition) but you
can so little with a function pointer that I worry less when I see a
"hidden pointer" typedef.
--
Ben.
.
- Follow-Ups:
- Re: Function Pointers
- From: Richard Heathfield
- Re: Function Pointers
- References:
- Function Pointers
- From: bwaichu@xxxxxxxxx
- Re: Function Pointers
- From: bwaichu@xxxxxxxxx
- Re: Function Pointers
- From: Vimal Aravindashan
- Re: Function Pointers
- From: Richard Heathfield
- Re: Function Pointers
- From: vippstar
- Re: Function Pointers
- From: Keith Thompson
- Re: Function Pointers
- From: bwaichu@xxxxxxxxx
- Re: Function Pointers
- From: Richard Heathfield
- Function Pointers
- Prev by Date: Re: When will exit(0) fail to exit?
- Next by Date: Re: Is this program standard conform?
- Previous by thread: Re: Function Pointers
- Next by thread: Re: Function Pointers
- Index(es):
Relevant Pages
|
Loading