Re: function pointers as function parameters
- From: Eric Sosman <eric.sosman@xxxxxxx>
- Date: Mon, 02 May 2005 14:40:12 -0400
Marlene Stebbins wrote:
> I am experimenting with function pointers. Unfortunately, my C book has
> nothing on function pointers as function parameters. I want to pass a
> pointer to ff() to f() with the result that f() prints the return value
> of ff(). The code below seems to work, but I would appreciate your
> comments. Have I got it right? Does the function name "decay" to a pointer?
It might be simpler to say that the function name "is"
a pointer to the function, since there is no context in
which it does anything other than "decay."
Your code is correct (as far as I can see), but there
are a few opportunities for stylistic improvement:
> #include <stdio.h>
> /* declares a function which takes an argument
> that is a pointer to a function returning an int */
> void f(int (*fptr)());
You know more about the pointed-to function than the
type of its returned value: specifically, you know that
it takes no arguments. (How do you know this? Because
you supply no arguments when you call it.) On the general
principle that it's best to tell the compiler everything
you know, write the declaration as
void f(int (*fptr)(void));
This way, the compiler will protest if you inadvertently
try to call the pointed-to function with arguments. If
you do in fact want to pass arguments, say so:
void f2(int (*fptr)(double, int, const char*));
> /* function returning an int */
> int ff(void);
>
> int main(void)
> {
> f(ff); /* pass the address of ff to f */
Here's where ff "decays."
> return 0;
> }
>
> void f(int (*fptr)())
If you've provided a prototype as suggested above,
you should also do so here.
> {
> int a;
> a = (*fptr)(); /* deref the func pointer */
This can also be written `a = fptr();' without the
parentheses and the asterisk. Some people prefer to write
the call as you've done it, saying that it draws attention
to the fact that a function pointer variable (rather than
a function identifier) is being used. I personally don't
buy that argument, noting that
(*printf)("Hello, world!\n");
is equally legitimate and (IMHO) equally silly. However,
de gustibus non disputandum est (Latin for "There's just
no arguing with Gus").
> printf("%d\n", a);
> return;
> }
>
> int ff(void)
> {
> return 2345;
> }
--
Eric.Sosman@xxxxxxx
.
- Follow-Ups:
- Re: function pointers as function parameters
- From: Keith Thompson
- Re: function pointers as function parameters
- From: pete
- Re: function pointers as function parameters
- References:
- function pointers as function parameters
- From: Marlene Stebbins
- function pointers as function parameters
- Prev by Date: Re: mutually referential (Pg 140 K&R2)
- Next by Date: Re: core dump on writing to pipe
- Previous by thread: function pointers as function parameters
- Next by thread: Re: function pointers as function parameters
- Index(es):
Relevant Pages
|