One of my teachers use this type declaration:
typedef void (*SortFunction)(int a[], int n);
to create a type that can hold a pointer to a function
and that can be used to call that function later on in a program.
I also know that to pass a function as a parameter you have to
wrap the function name in parenthesis and wrap the function’s
parameters in parenthesis after the function name as well like so
function someFunction( (anotherfunction)(type arg1, type arg2,...)){
...
}
What I want to know is why must you wrap a function in parenthesis like this? is this a built in function of most c++ compilers or is it simply a trick that we programmers use
in order to enable functions as arguments within our code? also, why does “SortFunction”
in the typedef statement need to be referenced, why can’t the variable you use to utilize SortFunction just hold the function instead of pointing to it?
There’s nothing special about function arguments. Whenever you declare a function pointer (as a local variable, global variable, class member variable, function parameter, typedef, etc.), it’s always declared like so:
Where
var_nameis the name of the function pointer variable. The reason the parentheses are needed around*var_nameis due to operator precedence: without the parentheses, the*(indicating that something’s a pointer) would match with the function’s return type, and instead you’d get something like a return type ofint*(pointer toint) instead of plainint.You can’t pass a function as an argument because functions are not first-class objects in C and C++. The only way to pass a function is my passing a pointer to the function.