6.2.3. Function Return, Part 1

function return, return, void return
Time: 00:01:37 | Download: Large, Large (CC), Small | Streaming, Streaming (CC) | Slides: PDF, PPTX

For the following discussion, it's convenient for us to categorize functions in two ways:

  1. functions that have a void return type, and
  2. functions that have a non-void return type.
The following figure summarizes the syntax for four situations that illustrate the two categories.
void function1()
{
    .
    .
    .

}
void function2()
{
    if (...)
        return;
    ...
    return;
}
int function3()
{
    .
    .
    .
    return value;
}
int function4()
{
    if (...)
        return value1;
    ...
    return value2;
}
(a)(b)(c)(d)
Returning from a function.
  1. A return statement is optional for functions with a void return type and a single exit point. Functions without an explicit return statement return automatically after running the last statement at the end of the function body.
  2. A function may have multiple return statements and each one defines a valid exit point. A return statement appearing anywhere except at the end of the function body is typically part of a branch.
  3. Functions with a non-void return type must have at least one return statement with an expression between "return" and the terminating semicolon. The expression can be a constant, a variable, or a more complex expression. The evaluated expression is the function's return value.
  4. Functions with multiple return statements can conditionally return different values, reflecting different problem conditions.
Some purists dislike functions with more than one exit point, but allowing multiple returns helps programmers write fast, efficient, and flexible functions.

 

double  calcPayment(double P, double R, int N)
{
    return P * R / (1 - pow(1 + R, -N));
}


double  calcPayment(double P, double R, int N)
{
    double    payment = P * R / (1 - pow(1 + R, -N));
    return payment;
    //return(payment);		// superfluous parentheses
}
(a)(b)
Returning a value. If the function returns a value (i.e., the return type is not void), then a return statement is required.
  1. Even short, simple non-void functions require a return statements.
  2. An alternate way of writing calcPayment using a temporary local variable.