I am reading C++ in easy steps and came across a piece of code for references and pointers that I do not understand.
The code is void (* fn) (int& a, int* b) = add;
. As far as I know it does not affect the program itself but would like to know what this code does.
#include <iostream>
using namespace std;
void add (int& a, int* b)
{
cout << "Total: " << (a+ *b) << endl;
}
int main()
{
int num = 100, sum = 200;
int rNum = num;
int* ptr = #
void (* fn) (int& a, int* b) = add;
cout << "reference: " << rNum << endl;
cout << "pointer: " << *ptr << endl;
ptr = ∑
cout << "pointer now: " << *ptr << endl;
add(rNum, ptr);
return 0;
}
Use the spiral rule:
+----------------------+
| +--+ |
| ^ | |
void (* fn ) (int& a, int* b) = add;
^ | | |
| +-----+ |
+---------------------------+
fn
is a pointer to a function taking two arguments (an int&
named a
and a int*
named b
) and returning void
. The function pointer is copy initialized with the free function add
.
So where in your code you have:
add(rNum, ptr);
That could be equivalently replaced by:
fn(rNum, ptr);
fn
is a pointer to a function taking, from left to right, an int&
, and an int*
, that does not return anything.
You are assigning the function add
to fn
.
You could call the function add
through the pointer, using exactly the same syntax as you would if you were use add
.
One use of this technique is in the modelling of callback functions. For example, qsort
requires a callback function for the sorting predicate. Function pointers are more common in C than in C++ where there are other techniques such as function objects, templates, lambdas, and even std::function
.
If you read about the clockwise/spiral rule the declaration is easy to decipher:
You declare a variable fn
, which is a pointer, to a function, taking some arguments and returning nothing.
Then you make this function-pointer fn
point to the add
function.
You can then use the function-pointer instead of calling add
directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With