Functions cannot return arrays or functions. They can, however, return references or pointers to arrays or functions. Another way to return an array is to declare a structure with only that array as a member:
struct Address
{ char szAddress[31]; };
Address GetAddress();
It is illegal to define a type in either the return-type portion of a function declaration or in the declaration of any argument to a function. The following legal C code is illegal in C++:
enum Weather { Cloudy, Rainy, Sunny } GetWeather( Date Today )
The preceding code is disallowed because the type Weather
has function scope local to GetWeather
and the return value cannot be properly used. Because arguments to functions have function scope, declarations made within the argument list would have the same problem if not allowed.
C++ does not support arrays of functions. However, arrays of pointers to functions can be useful. In parsing a Pascal-like language, the code is often separated into a lexical analyzer that parses tokens and a parser that attaches semantics to the tokens. If the analyzer returns a particular ordinal value for each token, code can be written to perform appropriate processing as shown in this example:
int ProcessFORToken( char *szText );
int ProcessWHILEToken( char *szText );
int ProcessBEGINToken( char *szText );
int ProcessENDToken( char *szText );
int ProcessIFToken( char *szText );
int ProcessTHENToken( char *szText );
int ProcessELSEToken( char *szText );
int (*ProcessToken[])( char * ) = {
ProcessFORToken, ProcessWHILEToken, ProcessBEGINToken,
ProcessENDToken, ProcessIFToken, ProcessTHENToken,
ProcessELSEToken };
const int MaxTokenID = sizeof ProcessToken / sizeof( int (*)() );
...
int DoProcessToken( int TokenID, char *szText )
{
if( TokenID < MaxTokenID )
return (*ProcessToken[TokenID])( szText );
else
return Error( szText );
}