Thread: Why pass a function as a parameter instead of just calling it normally?

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    101

    Why pass a function as a parameter instead of just calling it normally?

    I have been reading up on callbacks in C, but I am a bit confused. I know you can pass a function as a parameter just like any other variable / pointer, but why? Why not just call the function normally instead of through a passed pointer?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I think there are two major ways callbacks are used. It facilitates code reuse for one; when qsort() was invented, you were expected to use a callback to actually compare things in your array. Instead of rewriting qsort for every possible data entity, you only need to write part of it. So you'll see this used a lot in some libraries. For example, go here and look at all the typedefs of function pointers in the API and where they are used. Feel free to snoop around. And for two, slightly less often, you see a callback will be used in a place where something else could be used, like a switch.
    Last edited by whiteflags; 11-27-2011 at 07:38 PM.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Why not just call the function normally instead of through a passed pointer?
    What if the function needs to be called at some point in the future? A library, for example, might be able to call one of your functions if it encounters something unexpected. You pass it a function during the initialization phase, and the library stores a copy of the pointer somewhere. If an exceptional circumstance arises, it calls your function.

    If the function you pass your function pointer to calls the function immediately, with no new context, then sure, there's probably no need for it. But that's not what typically happens. Instead, it calls the function with some unknown data (this is whiteflags' qsort() example), or it calls it at some unknown time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 10-19-2009, 04:46 PM
  2. How pass NULL for a parameter in a function?
    By 6tr6tr in forum C++ Programming
    Replies: 2
    Last Post: 04-02-2008, 01:29 PM
  3. Replies: 3
    Last Post: 11-22-2007, 12:58 AM
  4. how would i pass on a vector pointer parameter
    By bugmenot in forum C++ Programming
    Replies: 5
    Last Post: 12-16-2005, 02:51 AM
  5. Parameter pass
    By Gades in forum C Programming
    Replies: 28
    Last Post: 11-20-2001, 02:08 PM