05. Function Pointers & Event Callbacks in C
🔴 Difficulty: Advanced | Executable Memory Addresses, Callbacks & qsort Integration
📖 Definition
A function pointer is a pointer variable that stores the entry point memory address of executable machine instructions for a function inside the binary's Text / Code Segment. Function pointers allow functions to be passed as arguments (Callbacks), stored in lookup tables, or assigned dynamically at runtime.
🎯 Why It Is Used
- Generic Library Sorting (
qsort): Passing custom comparison callbacks to standard library sorting routines. - Event-Driven Hardware Drivers: Registering interrupt service routine (ISR) callback handlers for button presses or network socket events.
- Polymorphic Dispatch Tables: Implementing Virtual Method Tables (Vtables) and state machine jump tables in C.
⚙️ How It Works: Function Pointer Syntax Parsing
In C declarations, function pointer syntax requires parentheses around the pointer name (e.g. int (*func_ptr)(int, int)) to distinguish a pointer returning an integer from a function returning an integer pointer (int *func_ptr(int, int)).
📝 Syntax
// 1. Direct Function Pointer Declaration
return_type (*pointer_name)(param1_type, param2_type);
// 2. Simplification using typedef
typedef return_type (*CallbackType)(param1_type, param2_type);
// 3. Assigning function address and executing call
pointer_name = &target_function; // or pointer_name = target_function;
return_type res = pointer_name(arg1, arg2); // or (*pointer_name)(arg1, arg2);
🔀 Function Pointer Table
| Declaration Pattern | Meaning |
|---|---|
int (*fn)(int, int); | Pointer to a function taking two ints and returning int. |
void (*handler)(const char*); | Pointer to an event handler taking a const char* and returning void. |
int (*comparator)(const void*, const void*); | ISO C standard comparison callback signature for qsort() and bsearch(). |
🌱 Beginner Example
#include <stdio.h>
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
int main(void) {
// Declare function pointer matching signature: int (int, int)
int (*operation)(int, int) = add;
printf("10 + 5 = %d\n", operation(10, 5));
// Reassign function pointer to multiply
operation = multiply;
printf("10 * 5 = %d\n", operation(10, 5));
return 0;
}
🌼 Intermediate Example: Event Callback Register System
#include <stdio.h>
typedef void (*EventListener)(int event_id);
void on_button_click(int event_id) {
printf("[UI Listener] Button Clicked! Event ID: %d\n", event_id);
}
void on_network_packet(int event_id) {
printf("[Network Listener] Packet Received! Event ID: %d\n", event_id);
}
void trigger_event(int event_id, EventListener listener) {
if (listener != NULL) {
listener(event_id); // Invokes passed callback function
}
}
int main(void) {
trigger_event(101, on_button_click);
trigger_event(202, on_network_packet);
return 0;
}
🌲 Advanced Example: Standard Library qsort() with Custom Comparator
#include <stdio.h>
#include <stdlib.h>
// Callback signature for qsort: int (*)(const void *, const void *)
int compare_integers_descending(const void *a, const void *b) {
int arg1 = *(const int*)a;
int arg2 = *(const int*)b;
if (arg1 > arg2) return -1; // -1 places larger numbers first (descending)
if (arg1 < arg2) return 1;
return 0;
}
int main(void) {
int numbers[] = {42, 12, 88, 3, 25, 67};
size_t count = sizeof(numbers) / sizeof(numbers[0]);
printf("Original Array : ");
for (size_t i = 0; i < count; i++) printf("%d ", numbers[i]);
printf("\n");
// Standard qsort library function accepting callback pointer
qsort(numbers, count, sizeof(int), compare_integers_descending);
printf("Sorted Descending: ");
for (size_t i = 0; i < count; i++) printf("%d ", numbers[i]);
printf("\n");
return 0;
}
🔍 Line-by-Line Explanation
int compare_integers_descending(const void *a, const void *b): ISO C standard callback template forqsort(). Operands are passed as genericconst void*pointers.int arg1 = *(const int*)a;: Casts genericvoid*toconst int*and dereferences it to read integer value.qsort(numbers, count, sizeof(int), compare_integers_descending);: Passes array pointer, element count, element size, and the function pointer callback tostdlib's quicksort algorithm.
💻 Expected Terminal Output
10 + 5 = 15
10 * 5 = 50
[UI Listener] Button Clicked! Event ID: 101
[Network Listener] Packet Received! Event ID: 202
Original Array : 42 12 88 3 25 67
Sorted Descending: 88 67 42 25 12 3
⚠️ Common Mistakes & Pitfalls
- Forgetting Parentheses in Declaration: Writing
int *func(int, int)declares a function returningint*instead of a function pointer! Always writeint (*func)(int, int). - Mismatched Callback Signatures: Passing a function pointer with wrong parameter types or return types causes undefined behavior during invocation.
📌 Important Rules & Limitations
- Function names decay into function pointers automatically when passed as arguments.
- Typedefs (
typedef void (*Callback)(int);) greatly simplify complex function pointer declarations.
🌐 Multilingual Explanation: English
A function pointer stores the RAM entry point address of executable code. Passing function pointers enables callback mechanisms, custom sorting comparators with qsort(), and event-driven architectures.
🌐 Multilingual Explanation: Hindi (Roman Script)
Function pointer executable code ka memory address store karta hai. Iska upyog functions ko doosre functions mein as argument (callbacks) bhejne ke liye aur qsort() jaise library functions mein hota hai.
🌐 Multilingual Explanation: Marathi (Roman Script)
Function pointer executable code cha RAM address store karto. Dynamic callbacks aani sorting algorithms (qsort) sathi function pointers vapartat.
❓ Practice Questions
- What is the difference between
int *f(int)andint (*f)(int)in C? - What signature must a comparator function implement to be passed to
qsort()? - How does
typedefsimplify complex function pointer syntax?
🚀 Practical Coding Challenge
Write a C program named calculator_callbacks.c that defines functions for add, subtract, and multiply. Create a higher-order function int execute_op(int a, int b, int (*op)(int, int)) that calls whatever operator function is passed to it.
🧭 Navigation & Breadcrumbs
← Previous: 04. Function Scope & Lifetime | Module 08 Guide | Next: 06. Variadic & Inline Functions →