A function pointer is a pointer that points to a function instead of a variable. It can be used to call a function dynamically, pass functions as arguments, and implement callbacks and event handlers.
Function pointers are declared by specifying the function’s return type, followed by an asterisk (*
), the pointer name, and the parameter types of the function it points to.
return_type (*pointer_name)(parameter_types);
#include <iostream>
using namespace std;
// Function to be pointed to
void display(int a) {
cout << "Value: " << a << endl;
}
int main() {
// Declare a function pointer
void (*funcPtr)(int) = display;
// Call the function using the pointer
funcPtr(10);
return 0;
}
In this example:
display
is a function that takes an integer parameter and returns void
.funcPtr
is a function pointer that points to display
.Function pointers can be used in various ways, including calling functions, passing them as arguments, and storing them in arrays.
You can call a function using a function pointer just as you would call a function directly.
#include <iostream>
using namespace std;
void display(int a) {
cout << "Value: " << a << endl;
}
int main() {
void (*funcPtr)(int) = display;
funcPtr(20); // Call the function using the pointer
return 0;
}
Function pointers can be passed as arguments to other functions, allowing for dynamic function calls and callbacks.
#include <iostream>
using namespace std;
void add(int a, int b) {
cout << "Sum: " << a + b << endl;
}
void subtract(int a, int b) {
cout << "Difference: " << a - b << endl;
}
void executeOperation(void (*operation)(int, int), int x, int y) {
operation(x, y);
}
int main() {
executeOperation(add, 10, 5); // Output: Sum: 15
executeOperation(subtract, 10, 5); // Output: Difference: 5
return 0;
}
In this example, executeOperation
takes a function pointer as an argument and calls the pointed-to function with the provided parameters.
You can store function pointers in arrays, allowing you to dynamically select and call functions.
#include <iostream>
using namespace std;
void add(int a, int b) {
cout << "Sum: " << a + b << endl;
}
void subtract(int a, int b) {
cout << "Difference: " << a - b << endl;
}
int main() {
// Array of function pointers
void (*operations[2])(int, int) = {add, subtract};
// Call functions using the array
operations[0](10, 5); // Output: Sum: 15
operations[1](10, 5); // Output: Difference: 5
return 0;
}