A C++ Callback Example
Home ] Up ] [ A C++ Callback Example ] A Java Callback Example ]

 

 

Imagine that you wish to write a function in C++ that goes through all the values in an array, and prints out all those values that match certain criteria, where the criteria are specified by calling back a supplied function.  The callback function is specified by passing in a pointer to that function.

Here's some C++ code that supports this, using callback functions. 

#include <iostream>
using namespace std;
typedef void select(int value);
static void greaterThan10(int value)
{
    if (value > 10)
        cout << " " << value;
}
static void lessThan20(int value)
{
    if (value < 20)
        cout << " " << value;
}
static void forEach(int vals[], size_t elements, select *callMe)
{
    for (int i = 0; i < elements; i++)
    {
        callMe(vals[i]);
    }
}
int main()
{
    int values[] = { 4, -5, 8, 37, 56, 2, 15, 92 };
    cout << "Values > 10 : ";
    forEach(values, sizeof(values)/sizeof(values[0]), greaterThan10);
    cout << endl;
    cout << "Values < 20 : ";
    forEach(values, sizeof(values)/sizeof(values[0]), lessThan20);
    cout << endl;
    return 0;
}

The output of this program is:

Values > 10 :  37 56 15 92
Values < 20 :  4 -5 8 2 15

In other words, each of the values in the array that matches the condition enforced in each callback function.

 

This page was last modified on 02 October, 2007