Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complicated pointer expressions

I have been reading Thinking in C++ vol1 and there is a section named Complicated declarations & definitions which depicts the following expressions, that I am not able to understand:

void * (*(*fp1)(int))[10];
float (*(*fp2)(int,int,float))(int);

Can anyone explain what the expressions mean, and how do you generally solve these kind of expressions?

Bruce has given the interpretations as follows:

fp1 is a pointer to a function that takes an integer argument and returns a pointer to an array of 10 void pointers.

fp2 is a pointer to a function that takes three arguments (int, int, and float) and returns a pointer to a function that takes an integer argument and returns a float

Although I have posted the correct answers, I would appreciate if someone would demonstrate the decoding of these expressions step by step.

like image 628
Manish Kumar Sharma Avatar asked Dec 19 '22 08:12

Manish Kumar Sharma


1 Answers

Here's a rule of thumb: start from the name of the variable and scan right until reaching a ) or the end of the declaration, then scan left until reaching ( or the beginning of the definition and then repeat.

So for the first example, start with the name, fp1. Looking right, you see a ), so now look left. You see a *, so you know that fp1 is a pointer. Then you reach a ( so go right again. The next character to the right is a ( which means function. Inside the parentheses is int so the function takes an int argument. So so far, you have a "pointer to function which takes an int argument" Next, you reach another ), so go left. You see a * so the return type is a pointer. Next you encounter a (, so you go to the right and see [10]. Of course, this means an array of size 10. So now you have a pointer to a function that takes an int parameter and returns a pointer to an array of size 10. Now you are at the farthest right, so scan left and you encounter void*. So from here, you have "a pointer to a function that takes an int parameter and returns a pointer to an array of size 10 which contains void pointers."

For the second example, follow a similar procedure.

like image 149
Daniel Avatar answered Dec 21 '22 21:12

Daniel