Mark As Completed Discussion

Function Pointers

In C++, a function pointer is a variable that stores the memory address of a function. It allows you to call functions indirectly using the pointer.

Declaring Function Pointers

To declare a function pointer, you need to specify the return type of the function and the types of its parameters. Here's the syntax:

TEXT/X-C++SRC
1return_type (*pointer_name)(parameter_types);

For example, to declare a function pointer that points to a function that takes two int parameters and returns an int, you would use the following declaration:

TEXT/X-C++SRC
1int (*sumPtr)(int, int);

Assigning Function Addresses to Pointers

To assign a function's address to a function pointer, you can use the & operator followed by the function's name. For example, to assign the address of a function add to a function pointer sumPtr, you would use the following assignment:

TEXT/X-C++SRC
1sumPtr = &add;

Calling Functions using Pointers

To call a function using a function pointer, you can use the function call operator (). For example, to call the function pointed to by sumPtr, you would use the following syntax:

TEXT/X-C++SRC
1int result = sumPtr(3, 4);

Example

Let's see an example that demonstrates the use of function pointers:

TEXT/X-C++SRC
1// Function to add two numbers
2int add(int a, int b) {
3  return a + b;
4}
5
6// Function to subtract two numbers
7int subtract(int a, int b) {
8  return a - b;
9}
10
11int main() {
12  // Declare function pointers
13  int (*sumPtr)(int, int);
14  int (*subPtr)(int, int);
15
16  // Assign function addresses to pointers
17  sumPtr = &add;
18  subPtr = &subtract;
19
20  // Call functions using pointers
21  int sum = sumPtr(4, 5);
22  int difference = subPtr(10, 7);
23
24  // Output results
25  cout << "Sum: " << sum << endl;
26  cout << "Difference: " << difference << endl;
27
28  return 0;
29}

In this example, we declare two functions add and subtract that take two int parameters and return an int. We then declare two function pointers sumPtr and subPtr. We assign the addresses of the add and subtract functions to the respective function pointers. Finally, we call the functions using the pointers and output the results.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment