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 afloat
Although I have posted the correct answers, I would appreciate if someone would demonstrate the decoding of these expressions step by step.
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.
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