The definition of a function consists of a function head (or the declarator) and a function block . The function head specifies the name of the function, the type of its return value, and the types and names of its parameters, if any. The statements in the function block specify what the function does. The general form of a function definition is as follows:
//function head
type function-name(parameter declarations)
//function block
{
declarations and statements
}
In the function head, name is the function's name, while type (return-type) consists of at least one type specifier, which defines the type of the function's return value. The return type may be void or any object type, except array types. Furthermore, type may include the function specifier inline, and/or one of the storage class specifiers extern and static.
A function cannot return a function or an array. However, you can define a function that returns a pointer to a function or a pointer to an array.
The parameterdeclarations are contained in a comma-separated list of declarations of the function's parameters. If the function has no parameters, this list is either empty or contains merely the word void.
The type of a function specifies not only its return type, but also the types of all its parameters. The following listing is a simple function to calculate the volume of a cylinder.
// The cylinderVolume( ) function calculates the volume of a cylinder.
// Arguments: Radius of the base circle; height of the cylinder.
// Return value: Volume of the cylinder.
extern double cylinderVolume( double r, double h )
{
const double pi = 3.1415926536; // Pi is constant
return pi * r * r * h;
}
This function has the name cylinderVolume, and has two parameters, r and h, both with type double. It returns a value with the type double.
return statement
The return statement ends execution of the current function, and jumps back to where the function was called:
expression is evaluated and the result is given to the caller as the value of the function call. This return value is converted to the function's return type, if necessary.
A function can contain any number of return statements:
// Return the smaller of two integer arguments.
int min( int a, int b )
{
if ( a < b ) return a;
else return b;
}
The contents of this function block can also be expressed by the following single statement:
return ( a < b ? a : b );
The parentheses do not affect the behavior of the return statement. However, complex return expressions are often enclosed in parentheses for the sake of readability.
A return statement with no expression can only be used in a function of type void. In fact, such functions do not need to have a return statement at all. If no return statement is encountered in a function, the program flow returns to the caller when the end of the function block is reached.