Passing functions as arguments
What you'll learn: How to make functions more flexible by passing other functions into them as parameters.
The "Plug-and-Play" Logic
Imagine you have a high-end coffee machine. The machine knows the process of making a drink (heat water, pump pressure), but it doesn't decide the flavor. You plug in a specific coffee pod to determine the final result.
In C, function pointers allow you to do the same thing with code. You can write a "boss" function that defines a process, but leaves one specific step open. When you call that boss function, you "plug in" a helper function to handle that step. This makes your code incredibly reusable because the boss function doesn't need to know the details; it just needs to know when to pull the trigger.
Seeing it in action
Let's say we want a function that performs an operation on two numbers. Instead of writing separate functions for add_and_print and multiply_and_print, we write one compute function that accepts a "math rule" as an argument.
#include <stdio.h>
// Two simple "helper" functions
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
// The "boss" function.
// It takes a pointer to ANY function that takes two ints and returns an int.
void compute(int x, int y, int (*operation)(int, int)) {
int result = operation(x, y);
printf("The result is: %d\n", result);
}
int main() {
// We pass the function names just like variables!
compute(5, 3, add); // Outputs: 8
compute(5, 3, multiply); // Outputs: 15
return 0;
}
Why bother?
In the example above, compute is the "boss." It handles the printing logic, while the passed-in function handles the math.
This is the secret sauce behind advanced C features like sorting algorithms. A generic sorting function knows how to move items around in an array, but it doesn't know if you want to sort by name, by date, or by size. By passing a "comparison function" as an argument, you tell the sorter exactly how to decide which item comes first without rewriting the whole sorting logic.
Key takeaway
Passing a function as an argument allows you to inject custom behavior into a generic process.