I’m reading some material about function pointer in C++, and come across one function definition which I do not understand.
Standard function definition have the form:
type name (param...)
But the following definition seems a little strange to me. Can anyone explain it to me ?
Thanks.
float (*GetPtr1(const char opCode)) (float, float)<br>
{
if(opCode == '+')
return &Plus;
else
return &Minus; // default if invalid operator was passed
}
Note: Plus and Minus are two functions with param (float, float) and return a float.
The rule for reading hairy declarations is to start with the leftmost identifier and work your way out, remembering that
()and[]bind before*(i.e.,*a[]is an array of pointers,(*a)[]is a pointer to an array,*f()is a function returning a pointer, and(*f)()is a pointer to a function):So, if
opCodeis equal to ‘+’,GetPtr1will return a pointer to the functionPlus, and if it’s ‘-‘, it will return a pointer to the functionMinus.C and C++ declaration syntax is expression-centric (much as Bjarne would like to pretend otherwise); the form of the declaration should match the form of the expression as it would be used in the code.
If we have a function
fthat returns a pointer tointand we want to access the value being pointed to, we execute the function and dereference the result:The type of the expression
*f()isint, so the declaration/definition for the function isNow suppose we have a function
f1that returns a pointer to the functionfdefined above, and we want to access that integer value by callingf1. We need to callf1, derefence the result (which is the functionf), and execute it, and then dereference that result (sincefreturns a pointer):The type of the expression
*(*f1())()isint, so the decaration/definition forf1needs to be