How to Declare Function Pointer in C: Syntax and Examples
In C, you declare a function pointer using the syntax
return_type (*pointer_name)(parameter_types). This pointer can then hold the address of a function with a matching signature and be used to call that function indirectly.Syntax
The general syntax to declare a function pointer is:
- return_type: The type of value the function returns.
- pointer_name: The name of the pointer variable, enclosed in parentheses and preceded by an asterisk
*. - parameter_types: The types of parameters the function accepts, inside parentheses.
This declares a pointer that can point to any function matching the specified return type and parameters.
c
return_type (*pointer_name)(parameter_types);
Example
This example shows how to declare a function pointer to a function that takes two int parameters and returns an int. It assigns the pointer to a function add and calls it through the pointer.
c
#include <stdio.h> int add(int a, int b) { return a + b; } int main() { int (*func_ptr)(int, int) = add; // Declare and assign function pointer int result = func_ptr(5, 3); // Call function via pointer printf("Result: %d\n", result); return 0; }
Output
Result: 8
Common Pitfalls
Common mistakes when declaring function pointers include:
- Missing parentheses around
*pointer_name, which changes the meaning. - Mismatching the function signature (return type or parameters) between the pointer and the function.
- Forgetting to assign the pointer before calling it, leading to undefined behavior.
Here is an example showing a wrong and right declaration:
c
// Wrong: missing parentheses, declares a function returning pointer int *func_ptr_wrong(int, int); // Right: parentheses around *func_ptr declare a pointer to function int (*func_ptr_right)(int, int);
Quick Reference
| Concept | Example |
|---|---|
| Declare pointer to function returning int with two int params | int (*ptr)(int, int); |
| Assign pointer to function named add | ptr = add; |
| Call function via pointer | int result = ptr(2, 3); |
| Pointer to function returning void with no params | void (*ptr)(void); |
Key Takeaways
Use parentheses around *pointer_name to declare a function pointer correctly.
The function pointer's signature must exactly match the function it points to.
Assign the function's name (without parentheses) to the pointer before calling.
Call the function through the pointer using normal function call syntax.
Function pointers allow flexible and dynamic function calls in C.