C Callback Functions
1. What is a Callback Function?
-
A callback function is a function passed as an argument to another function.
-
The receiving function can call the passed function at a specific point.
-
Enables dynamic behavior and is widely used in:
-
Event handling
-
Sorting/comparison functions
-
Library APIs
-
2. How Callback Functions Work
-
Define a function that performs a task.
-
Define another function that accepts a function pointer as a parameter.
-
Pass the function pointer to the second function.
-
Call the function via the pointer inside the second function.
3. Basic Example: Using a Callback Function
Output:
greetUseris passed as a callback toprocessName.
4. Example: Using Callback with Sorting (Comparison Function)
-
The C library function
qsort()uses a callback function for comparison.
Output:
The
comparefunction is called byqsort()each time it needs to compare elements.
5. Advantages of Callback Functions
-
Flexibility: Allows the called function to use different behaviors dynamically.
-
Modularity: Separates generic functions from specific operations.
-
Reusability: You can reuse the same function with different callbacks.
-
Event-driven programming: Useful in GUIs, interrupts, and library APIs.
6. Key Points About Callback Functions
-
A callback is implemented using a function pointer.
-
The function pointer must match the signature of the actual function.
-
Widely used in sorting, searching, event handling, and library functions.
-
Enables higher-order programming in C.
