Dec 11, 2007
Callback function
/** $g++ callback.c -o callback
./callback
Item 4
http://en.wikipedia.org/wiki/Callback_%28computer_science%29
*/
#include
/* LIBRARY CODE */
int traverseWith(int array[], size_t length,
int (*callback)(int index, int item, void *param),
void *param)
{
int exitCode = 0;
for (int i = 0; i < length; i++) {
exitCode = callback(i, array[i], param);
if (exitCode != 0) {
break;
}
}
return exitCode;
}
/* APPLICATION CODE */
int search (int index, int item, void *param)
{
if (item > 5) {
*(int *)param = index;
return 1;
} else {
return 0;
}
}
main()
{
/* (in another function) */
int index;
int found;
int array[] = {1, 2, 3, 4, 7, 10, 12, 15 };
int length = 6;
found = traverseWith(array, length, &search, &index);
if (found) {
printf("Item %d\n", index);
} else {
printf("Not found\n");
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment