Table of Contents
A function pointer is a pointer that stores the address of a function. It allows a function to be called indirectly through the pointer instead of using its name directly.
The type of a function pointer is determined by the function’s return type and parameter types. Function pointers are useful when a program needs to select or pass functions dynamically, such as implementing callbacks or dispatch tables.
Source Code #
#include <iostream>
int add(int first, int second)
{
return first + second;
}
int main()
{
int (*operation)(int, int) = add;
int result = operation(10, 20);
std::cout << "Result: " << result << '\n';
return 0;
}
Output #
Result: 30
Explanation #
int (*operation)(int, int)declaresoperationas a pointer to a function.- The pointer can point to a function that returns
intand accepts twointparameters. = addinitializes the function pointer with the address of theadd()function.operation(10, 20)calls the function through the function pointer.- The function pointer call produces the same result as directly calling
add(10, 20). - The function’s return type and parameter types must be compatible with the function pointer’s type.
- Function pointers can be passed to other functions and used to select different functions at runtime.
return 0;terminates the program successfully.