C callbacks
Created By: chatGPT
In C programming, callbacks are functions that are passed as arguments to other functions. This allows for dynamic behavior and can be used to implement a variety of patterns, such as event handling or asynchronous processing. To use a callback, you typically define a function prototype matching the callback's expected signature, create a specific function that implements this prototype, and then pass the function name as a parameter to the invoking function.
#include <stdio.h>
// Callback function type definition
typedef void (*Callback)(int);
// A function that takes a callback as an argument
void performAction(int value, Callback cb) {
// Call the callback function with the value
cb(value);
}
// Example callback function
void myCallback(int x) {
printf("Callback called with value: %d\n", x);
}
int main() {
// Using the callback
performAction(42, myCallback);
return 0;
}
In the example above, we defined a callback type using a typedef for better readability. The
performAction
function takes an integer and a pointer to a callback function. Inside this function, the callback is invoked with the provided integer. The myCallback
function matches the signature of the callback type and prints the value it receives.
// Another example using a different callback
void anotherCallback(int y) {
printf("Another callback with value: %d\n", y);
}
int main() {
// Using a different callback
performAction(21, anotherCallback);
return 0;
}
You can also use function pointers more extensively. If you have a list of functions, you could store them in an array and loop through them, invoking each callback in turn.
#define NUM_CALLBACKS 3
void callback1(int x) {
printf("Callback 1: %d\n", x);
}
void callback2(int x) {
printf("Callback 2: %d\n", x);
}
void callback3(int x) {
printf("Callback 3: %d\n", x);
}
int main() {
// Array of callbacks
Callback callbacks[NUM_CALLBACKS] = {callback1, callback2, callback3};
int value = 100;
// Loop through the callbacks and invoke each one
for (int i = 0; i < NUM_CALLBACKS; i++) {
callbacks[i](value);
}
return 0;
}