Function pointers
- C course
- Intermediate
- Lesson 3/116
- 5 min
Learn to define and call function pointers.
What is a function pointer?
A function pointer holds the address of a function. In C the syntax int (*fp)(int); declares a pointer to a function returning int and taking one int.
Example: int square(int x) { return x * x; } and int (*fp)(int) = square;. Here fp holds the address of square. To call it you write fp(5) or (*fp)(5); both return 25. A function pointer lets you choose the function to call at runtime.
Calling a function pointer
You can call a function pointer in two ways: fp(arg) or (*fp)(arg). Both are valid and give the same result.
The first form is more common; the second makes the indirection explicit. What matters is that the pointer's declaration matches the function signature exactly. If the return type or parameter list differs, the behaviour is undefined. That is why function pointer types, though long, must be written in full.
Practice Square via a function pointer
Write a function int square(int x) that returns x * x. Declare a pointer of type int (*fp)(int) and assign it to square. Call fp(7) and print the result with printf.
Starter code
#include <stdio.h>
// Write the square function
// Declare fp and assign it to square
// Print the result of the fp call
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int square(int x) {
return x * x;
}
int main(void) {
int (*fp)(int) = square;
printf("%d\n", fp(7));
return 0;
}Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a pointer to a function returning int and taking int?
- int (*fp)(int);
- int *fp(int); Correct answer
- int fp*(int);
- (int *)fp(int);
Explanation: Int (*fp)(int); — the parentheses make fp a pointer.
2 Match the function pointer parts
| Term | Meaning |
|---|---|
int |
Return type |
(*fp) |
Pointer variable |
(int) |
Parameter list |
fp(5) |
Call |
3 Call the function pointer
int square(int x) { return x * x; }
int (*fp)(int) = square;
int r = ____(5);
int square(int x) { return x * x; }
int (*fp)(int) = square;
int r = fp(5);
Explanation: fp can be called like a function directly.