6.2.3. Function Return, Part 1

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

For the following discussion, it's convenient for us to categorize functions 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 generalizes the syntax for four situations illustrating 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. 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, appearing anywhere in the function. If the function has a void return type, it doesn't include an expression between the return and the terminating semicolon.
  3. Functions with a non-void return type must have at least one return statement with an expression between the keyword and the terminating semicolon. The evaluated expression is the function's return value.
  4. Functions with multiple return statements can conditionally return different values, reflecting different problem conditions.
A return statement at the bottom of a function, (a) and (c), can stand alone, but additional return statements, typically incorporated in the function's problem-solving logic, (b) and (d), are enclosed in branches (if- or switch-statements). Some purest 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.