Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding declaration in C++

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 = &num;

    void (* fn) (int& a, int* b) = add;

    cout << "reference: " << rNum << endl;
    cout << "pointer: " << *ptr << endl;

    ptr = &sum;
    cout << "pointer now: " << *ptr << endl;
    add(rNum, ptr);
    return 0;
}
like image 736
Sulaco-Lv223 Avatar asked Aug 03 '15 13:08

Sulaco-Lv223


3 Answers

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);
like image 117
Barry Avatar answered Oct 21 '22 19:10

Barry


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.

like image 35
Bathsheba Avatar answered Oct 21 '22 18:10

Bathsheba


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.

like image 4
Some programmer dude Avatar answered Oct 21 '22 19:10

Some programmer dude