Understanding Declaration in C ++

I read C ++ in simple steps and came across a piece of code for links and pointers that I don't understand.

Code void (* fn) (int& a, int* b) = add; . As far as I know, this does not affect the program itself, but I 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; } 
+5
c ++ pointers reference
source share
5 answers

Use the spiral rule:

  +----------------------+ | +--+ | | ^ | | void (* fn ) (int& a, int* b) = add; ^ | | | | +-----+ | +---------------------------+ 

fn is a pointer to a function that takes two arguments (a int& with the name a and a int* with the name b ) and returns void . A function pointer is a copy initialized by the free add function.

So where in your code is:

 add(rNum, ptr); 

This can be equivalently replaced with:

 fn(rNum, ptr); 
+11
source share

fn is a pointer to a function taken from left to right, int& and int* , which returns nothing.

You assign the add function to fn .

You can call the add function through a pointer using the same syntax as you would if you used add .

One application of this method is to model callback functions. For example, qsort requires a callback function for a sort predicate. Function pointers are more common in C than in C ++, where there are other methods such as function objects, templates, lambdas, and even std::function .

+7
source share

If you read the rule clockwise / spiral , the declaration is easily decrypted:

You declare the variable fn , which is a pointer, to the function, taking some arguments and not returning anything.

Then you make this fn pointer function point to the add function.

Then you can use the function pointer instead of calling add directly.

+4
source share

void (* fn) (int& a, int* b) = add; declares a function pointer named fn , which indicates that it points to a function with signature void(int&,int*) . it then integrates a pointer to the add() function.

+3
source share

Such complex declarations are easy to read using the right-left rule, which works even when clockwise rotation is not performed , which makes even in the case of something simple, like int* a[][10] .

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

Start with the identifier fn and go from right to left, the brackets turn the direction. Thus, fn is a pointer to the execution of the function, referring to int and a pointer to int , and the return type of the function is void .

He called reading boustrophedonically . See this answer for another example.

+1
source share

All Articles