declaring a function whose arg is another function

  • I have a problem having to do with the right C-code for declaring and
    calling a function which has another function as argument.
    I've tried to find the answer in Harbison/Steele, without success.

    Consider a function like foo:

    void foo(int arg);

    and another C-function, bar, that has as argument a function like
    foo, and returns nothing.

    Question 1: how do I declare bar? One of these ways?
    void bar(void fcn(int));
    void bar(void (*fcn)(int));
    void bar(void (*fcn)());

    Question 2: how do I call bar with foo as argument? Like one of these?
    bar(foo);
    bar(&foo)

    Question 3: Is this the right list to post this kind of question? If
    not, where?

    -- Roland Silver <rollos...>
  • On 24 Sep 2007, at 12:29, Roland Silver wrote:

    > I have a problem having to do with the right C-code for declaring
    > and calling a function which has another function as argument.
    > I've tried to find the answer in Harbison/Steele, without success.
    >
    > Consider a function like foo:
    >
    > void foo(int arg);
    >
    > and another C-function, bar, that has as argument a function like
    > foo, and returns nothing.
    >
    > Question 1: how do I declare bar? One of these ways?
    > void bar(void fcn(int));
    > void bar(void (*fcn)(int));
    > void bar(void (*fcn)());

    The middle one is best; the top one won't work at all, and the bottom
    one means different things in C and C++.  But people normally write

      typedef void (*callback_fn_t)(int arg);

    and then do

      void bar (callback_fn_t callback);

    because (a) it's easier to read (often easier to type too), and (b)
    you sometimes find yourself wanting to cast your callback function
    (e.g. because of minor type differences).

    > Question 2: how do I call bar with foo as argument? Like one of these?
    > bar(foo);
    > bar(&foo)

    You don't need the "&".  Likewise, you don't need to write e.g.
    (*callback)(5)... you can just do callback(5).  Pointer-to-function
    variables are generally interchangeable with function names (similar
    to the way that pointer variables are generally interchangeable with
    array names).

    > Question 3: Is this the right list to post this kind of question?
    > If not, where?

    Not really, no.  comp.lang.c is the canonical place for C questions
    (which is what this is), or you could try a more general purpose list
    (e.g. Omni's macosx-dev list).

    This should really be obvious... just ask yourself: Is this question
    about *Cocoa*?  If the answer is "No", then this is not the right
    mailing list.

    Kind regards,

    Alastair.

    --
    http://alastairs-place.net
previous month september 2007 next month
MTWTFSS
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Go to today