Callback Function in the C Computer Language
Part 31 of the Complete C Course
Foreword: Callback Function in the C Computer Language
By: Chrysanthus Date Published: 22 Jun 2024
Introduction
#include <stdio.h>
void cbFn(char stri[], char cha) {
printf("%s", stri);
printf("%c\n", cha);
}
void princFn (int no, void (*func)(char stri[], char cha)) {
char str[] = "We are learning ";
char ch = 'C';
(*func)(str, ch);
}
int main(int argc, char *argv[])
{
princFn(10, cbFn); //principal function call
return 0;
}
In C, in practice, the coded definition of the callback function, is separated from the principal function. In the above program, after the inclusion of the stdio library header, "stdio.h" the callback function is defined. After the definition of the callback function, is the definition of the principal function. In the definition of the principal function, the second parameter in its signature, is the signature of a pointer to a function. This pointer to a function has the same parameters and return type as the callback function. The last statement in this principal function definition, is a function call by pointer, with arguments, corresponding to this second parameter, with same function name.
In the C main() function, the call to the principal function is:
princFn(10, cbFn);
The second argument here, is the callback function name without parentheses and arguments. The arguments were sent within the definition of the principal function. The output of the program is:
We are learning C