Restrictions on Functions

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:

// restrictions_to_functions.cpp
// The following functions are user-defined
int Error( char *szText) {return 1;}
int ProcessFORToken( char *szText ) {return 1;}
int ProcessWHILEToken( char *szText ){return 1;}
int ProcessBEGINToken( char *szText ){return 1;}
int ProcessENDToken( char *szText ){return 1;}
int ProcessIFToken( char *szText ){return 1;}
int ProcessTHENToken( char *szText ){return 1;}
int ProcessELSEToken( char *szText ){return 1;}

int (*ProcessToken[])( char * ) = {
   ProcessFORToken, ProcessWHILEToken, ProcessBEGINToken,
   ProcessENDToken, ProcessIFToken, ProcessTHENToken,
   ProcessELSEToken 
};

const int MaxTokenID = sizeof ProcessToken / sizeof( int (*)(char*) );

int DoProcessToken( int TokenID, char *szText ) {
   if( TokenID < MaxTokenID )
      return (*ProcessToken[TokenID])( szText );
   else
      return Error( szText );
}

int main()
{
}

See Also

Reference

Function Declarations