Callback functions are functions whose addresses are passed as arguments to other functions. This allows for implementing event handlers, custom algorithms, and plugins.
Declaring a callback function:
typedef void (*callback_func_t)(int);
void process(callback_func_t cb) { // ... cb(42); // call the callback } void handler(int n) { printf("Processed number: %d\n", n); } int main() { process(handler); return 0; }
Tips:
Can a function with a non-matching signature be passed as a callback?
Common incorrect answer: "Yes, C will allow this if you declare an explicit cast."
Correct answer: Although formal casting is possible, calling such a function will lead to undefined behavior—incorrect values may be passed to parameters, and the stack may become corrupted.
Example of danger:
typedef void (*cb_t)(int); void wrong_cb(double d) { printf("%f\n", d); } void call(cb_t f) { f(123); } int main() { call((cb_t)wrong_cb); } // DANGEROUS: signatures differ
Story
Story
Story
When developing a cross-platform system, the author incorrectly defined the calling convention for callback functions. This did not manifest on one OS but caused the program to crash on another when calling callbacks from the C library.