Function pointers in C: solved exercise with callbacks
Function pointers in C: solved exercise step by step
If you searched for a solved function pointer exercise in C, here are the three most common uses: direct call, function table, and callback in qsort.
A function pointer stores the address of a function with a specific signature. It lets you choose which function to invoke at runtime without needing switch or if-else.
Function pointer syntax
For example, a pointer to a function that takes two int arguments and returns int:
Problem statement
- Define four basic arithmetic operations as separate functions.
- Call one of them through a function pointer.
- Create a table (array) of function pointers to iterate over all operations.
- Use a function pointer as a callback in
qsortto sort an integer array in descending order.
C solution
Expected output
Common mistakes
- Forgetting parentheses in the declaration:
int *f(int)declares a function returningint*, not a function pointer. - Mismatching the pointer signature with the assigned function’s signature.
- In
qsort, using a plain subtraction (return a - b) can overflow with large integers; the safe form isreturn (a > b) - (a < b). - Calling a
NULLfunction pointer without checking.
Practical use
Function pointers appear in:
- sorting callbacks (
qsort,bsearch), - plugin systems or interchangeable strategies,
- state machines where each state has its own processing function,
- C APIs that accept user-supplied functions (signals, threads).
Recommended next exercise
- calloc in C: solved exercise
- Pointer to pointer in C: solved exercise
- Quicksort in C: solved exercise
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
What is the difference between (*op)(x, y) and op(x, y)?
Both forms are equivalent in C. The first explicitly dereferences the pointer; the second uses the shorthand notation accepted since C89. The second form is more common in modern code.
Can I pass a function pointer as an argument?
Yes. That is the callback mechanism: void apply(int a, int b, int (*f)(int, int)) { printf("%d\n", f(a, b)); }.
Are function pointers safe?
They are safe as long as they point to a valid function. The risks are calling a NULL pointer without checking, or assigning a function with an incompatible signature (undefined behavior).