Some programmer dude answered the question you're actually asking.
To answer the title of the question, no, a function cannot return a value of function type (i.e., a function cannot return another function). However, a function can return a value that's a pointer to a function type:
/**
* Returns a pointer to a search function
*/
bool (*get_func( /* lookup params */ ))(int, int *, int)
{
...
if ( /* lookup params indicate binary search */ )
return binary_search; // note that we return the function name only
...
}
/**
* get_func returns a pointer to one of several different searching
* functions, based on the type of search we want to perform
*/
bool (*search_func)(int, int *, int ) = get_func( /* lookup params */);
/**
* Execute the searching function on values through the search_func
* pointer.
*/
if ( search_func != NULL && search_func( value, values, n ) )
// do something
The way to read the declaration of get_func
is
get_func -- get_func
get_func( ) -- is a function taking
get_func( /* lookup params */ ) -- some parameters (won't get into details here )
*get_func( /* lookup params */ ) -- returning a pointer
(*get_func( /* lookup params */ ))( ) -- to a function taking
(*get_func( /* lookup params */ ))(int ) -- parameter unnamed of type int
(*get_func( /* lookup params */ ))(int, int * ) -- parameter unnamed of type int *
(*get_func( /* lookup params */ ))(int, int *, int) -- parameter unnamed of type int
bool (*get_func( /* lookup params */ ))(int, int *, int) -- returning bool
Similar to how array expressions "decay" to pointer expressions, a function expression will automatically be converted to a pointer expression as well. When we write return binary_search
in get_func
, we're not calling binary_search
; instead, the binary_search
expression is converted from type "function returning bool
" to "pointer to function returning bool
". Note that the return type (bool
) and the number and types of parameters (int
, int *
, and int
) must all match up between the search_func
pointer, the get_func
function, and the actual binary_search
function.
A typedef makes this easier to read:
/**
* searchFuncType is an alias for type "function taking an int,
* int *, and int, and returning a bool"
*/
typedef bool searchFuncType( int, int *, int );
...
searchFuncType *get_func( /* lookup params */ )
{
...
return binary_search;
...
}
...
searchFuncType *searchFunc = get_func( /* lookup params */ );
...
although I prefer to use "naked" types, unless I intend to hide that type behind an API.