Calling function pointers
- C course
- Intermediate
- Lesson 25/116
- 5 min
Learn to call function pointers.
Two ways to call
You can call a function pointer in two ways: directly fp(arg) or indirectly (*fp)(arg). Both are valid and give the same result.
Example: after defining int (*fp)(int) = negate;, both fp(7) and (*fp)(7) return -7. The first form is more common and shorter. The second makes the indirection explicit; some old code prefers it. Which to use is a style choice; modern C commonly uses fp(arg) directly.
When to use a function pointer?
A function pointer is used when you want to choose the behavior at runtime. For a fixed function call it's unnecessary.
For example in a calculator the user may enter 'add' or 'sub'; you keep a function pointer and call it. Or a sort algorithm takes the comparison via a function pointer (like qsort). Calling a fixed function directly is simpler; a function pointer earns its place when flexibility is needed. That's why real-world code shows it only in specific patterns.
Practice Call both ways
Write int negate(int x) returning -x. Declare the pointer with int (*fp)(int) = negate;. Call both ways: printf("%d\n", fp(7)); and printf("%d\n", (*fp)(7));.
Starter code
#include <stdio.h>
// Write the negate function
// Declare the fp pointer
// Call fp both ways and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int negate(int x) {
return -x;
}
int main(void) {
int (*fp)(int) = negate;
printf("%d\n", fp(7));
printf("%d\n", (*fp)(7));
return 0;
}Expected output
-7 -7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the call forms
| Term | Meaning |
|---|---|
fp(7) |
Direct call |
(*fp)(7) |
Indirect call |
fp = negate |
Assignment |
int (*fp)(int) |
Type |
2 What's the relation between fp(7) and (*fp)(7)?
- fp(7) is invalid
- (*fp)(7) is invalid
- They give the same result Correct answer
- They give different results
Explanation: Both forms call the function pointer; same result.
3 Complete the indirect call
int (*fp)(int) = negate;
int r = (____)(7);
int (*fp)(int) = negate;
int r = (*fp)(7);
Explanation: (*fp)(7) is the indirect call.