0

I want to know where callback functions are actually used ?

And is there a way to implement callback function ( other than using function pointer ) in C/C++ ?

Please explain the following line -

"A callback can be used as a simpler alternative to polymorphism and generic programming"

Thanks

Vikram
  • 1,999
  • 3
  • 23
  • 35
  • May be a duplicate of http://stackoverflow.com/questions/142789/what-is-a-callback-in-c-and-how-are-they-implemented – Jay Mar 06 '12 at 13:28
  • 2 examples: [the C standard library's qsort function](http://pubs.opengroup.org/onlinepubs/009695399/functions/qsort.html) and [Asynchronous I/O](http://en.wikipedia.org/wiki/Asynchronous_I/O#Callback_functions) - I won't go into more detail as I have a feeling this is for an assignment. – pmdj Mar 06 '12 at 13:29
  • @Jay I already gone through it .. I was asking for application not for implementation ! Just like Core Audio programming is one mentioned there ! – Vikram Mar 06 '12 at 13:43

4 Answers4

6

I want to know where callback functions are actually used ?

The two most common uses are to allow the user to implement part of an algorithm (for example, the comparators passed to C's qsort and C++'s std::sort to allow sorting of arbitrary types), and to receive notification of external events (for example, in many asynchronous user interface and communications libraries, such as Boost.Asio).

And is there a way to implement callback function ( other than using function pointer ) in C/C++ ?

There is no such language as C/C++.

In C, the only sensible mechanism is a function pointer.

In C++ there are many ways. One common method, for those who like OOP, is to define an abstract interface class. The virtual functions declared there act as callbacks, and can call arbitrary code defined in a derived implementation class.

Those who like generic and functional programming would instead define a class that overloads operator() - often called a "functor" or "function object". Such a thing can be called like a function, but can also carry state with it. This pattern is widely used throughout the standard library, for example to provide custom allocators for containers and custom comparators for sorting algorithms.

Both methods make it much more convenient to provide extra information to the callback - perhaps an object to call a member function on, or a value to compare a function argument with. In C, any such "user" state would have to be passed via an extra argument in the callback - and if the designer of the callback mechanism neglected to include that, then it can be quite tricky to use.

C++11 provides some convenient new ways to handle functors. std::function is a polymorphic type that can represent any kind of function-like thing, and is a good type to use for a callback if you don't want to template over the function type. std::bind and lambda expressions are simple ways to define a functor from some arbitrary piece of code.

A callback can be used as a simpler alternative to polymorphism and generic programming

Out of context, that doesn't make a lot of sense. I guess that means that, if you use a function pointer for a callback, you don't need to define any abstract interfaces or functors. Some might regard that as simpler, if they think that polymorphism and genericity are complicated; however it also brings its own complications, since there is no type-safe way to pass arbitrary user data to the callback, as there is with the C++ methods.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

An example is qsort. You pass a callback function to determine the ordering of elements.

I'm not sure how callbacks are simpler than polymorphism, unless you coded in C for 50 years and have never worked with OOP. Polymorphism is a central OOP concept and is not only related to C++, whereas not all OOP languages have function pointers.

But it's true, in pure C you can simulate polymorphism via function pointers.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Callbacks are simpler in cases where you don't wish to create an entire class to be the delegate of some function. I especially like them with Apple blocks, which is where they really shine. – Richard J. Ross III Mar 06 '12 at 14:11
  • @RichardJ.RossIII: True, but these days "creating an entire class to be the delegate" is as simple as writing a lambda expression - and simpler than creating an entire function to be the delegate. – Mike Seymour Mar 06 '12 at 14:14
  • @MikeSeymour 'creating a lambda' is not possible in standard C / C++ which is what this question is about. Which is why I brought up apple blocks, as they act as an anonymous delegate from C# for the most part, but are a function pointer behind the scenes. – Richard J. Ross III Mar 06 '12 at 14:16
  • @RichardJ.RossIII: It's been possible in Standard C++ for about 6 months now. – Mike Seymour Mar 06 '12 at 14:17
  • @MikeSeymour by standard C I meant C99, and by standard C++ I meant C++2003, as those are the versions supported by most compilers right now. – Richard J. Ross III Mar 06 '12 at 14:18
  • @RichardJ.RossIII: OK, I take "standard" to mean the current standard; and current versions of most major compilers support lambdas. You're certainly correct that, before lambdas existed, defining a function involved slightly less typing than defining a function-like class, as long as you didn't need to pass any complex state to it. – Mike Seymour Mar 06 '12 at 14:21
1

The meaning of a callback function is: a function that is not called by the programmer anywhere in their code, but called from an external source. Typically, this means the OS.

  • If the external source calling the function is hardware, the called function is named "interrupt service routine".
  • If the external source is software, the called function is named "callback function."

For example, you will find plenty of callback functions in Windows programming. Every graphical window has a callback function "WindowProc" that receives a call from the OS for every action occurring on the window. It is then up to the application programmer to write the callback function and handle the events they are interested in. Events that they aren't interested in is passed to the default handler (or base class, if you will).

If the programmer wants something special to happen when the mouse is clicked on a window, they can overwrite the default behavior of a mouse click, by replacing the default behavior with their own code. This way you achieve polymorphism, even in C programs.

Example from Windows programming:

LRESULT CALLBACK WindowProc (HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam)
{
  switch(umsg)
  {
    case WM_LBUTTONDOWN:

      do_something(); /* overwrite default behavior of a left mouse button click */

      break; /* break = and then execute the default behavior afterwards */

    case WM_RBUTTONDOWN:

      do_something(); /* overwrite default behavior of a right mouse button click */

      return 0; /* overwrite the default behavior entirely */

  }    


  // execute default behavior for the event:
  return DefWindowProc(hwnd, umsg, wparam, lparam);
}

The break from the switch statement is similar to plain inheritage: execute the inherited function and then the base class function. While the return 0; is similar to polymorphism/virtual inheritage, since the inherited object overwrites default behavior entirely.


A sidenote: Since a callback function is called from an external source and not the program itself, some of the dumber compilers will make assumptions that the function is never called and therefore perform dangerous optimizations.

For example, had the global variable "flag" been modified from the WindowProc above, and code in main() relies on "flag", the compiler would possibly optimize away the code in main(), since it believes that "flag" was never used anywhere.

To avoid this incorrect compiler behaviour, it is good practice to always declare all variables shared between a callback function and the rest of the program as volatile, which will block all optimizations of that variable.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

I want to know where callback functions are actually used ?

GUI programming. On windows platform, when you want to make window you pass a callback function to the system that controls window behavior. Of course, high-level frameworks will hide this behavior, but it is still here.

Multithreading, asynchronous IO, also, when you want to make system process something using user-defined function (example is qsort).

Basically, you can't live without callbacks if you want to make extensible code that should interact with multiple languages.

SigTerm
  • 26,089
  • 6
  • 66
  • 115