Function Pointers and Callbacks
Function pointers allow you to create variables that can store the address of functions. This enables dynamic function invocation and can be used for implementing callback mechanisms.
#include <stdio.h>
void greet() {
printf("Hello!\n");
}
void farewell() {
printf("Goodbye!\n");
}
void invoke(void (*function)()) {
function();
}
int main() {
void (*callback)(); // Function pointer declaration
callback = greet; // Assign address of greet function
invoke(callback); // Call greet function through function pointer
callback = farewell; // Assign address of farewell function
invoke(callback); // Call farewell function through function pointer
return 0;
}
No comments:
Post a Comment