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

This is a discussion on Why pass a function as a parameter instead of just calling it normally? within the C Programming forums, part of the General Programming Boards category; I have been reading up on callbacks in C, but I am a bit confused. I know you can pass ...

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

    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
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,741
    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 06:38 PM.

  3. #3
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    991
    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-21-2007, 11:58 PM
  4. how would i pass on a vector pointer parameter
    By bugmenot in forum C++ Programming
    Replies: 5
    Last Post: 12-16-2005, 01:51 AM
  5. Parameter pass
    By Gades in forum C Programming
    Replies: 28
    Last Post: 11-20-2001, 01:08 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21