Skip to main content
Logo image

Section 29.2 Callback Functions

A callback function is simply a function that is passed as an argument into another function, so that the other function can “call it back” when it needs it— this is done using function pointers. Callbacks let us write generic, reusable code once, and then reuse it many times by passing in a different callback to handle the custom computation. The only strict rule is that the functions being swapped around must all share the same prototype.
Here’s the simplest possible example— a function that repeats any no-argument, no-return function three times:

admin.....open in new window

Callbacks become more useful once the callback itself takes and returns values. In the example below, calculate() doesn’t know or care whether it’s squaring, cubing, or taking a square root— it just calls whatever function op currently points to:

admin.....open in new window

Activity 29.3.

Let’s upgrade our Bubble Sort code so that it can sort numbers in either ascending or descending order. The only thing that determines the sort order is the comparison if (array[i] > array[i+1]). Write two callback functions:
  • int ascending(int a, int b)— returns 1 if a > b
  • int descending(int a, int b)— returns 1 if a < b
Modify your Bubble Sort function to accept a callback as an extra argument, and inside the sort, replace your hardcoded if statement with a call to that callback. Test your code to sort in both ascending and descending order.

admin.....open in new window

Record your code below.