C++ Notes: Function return Statement

Return statement

The return statement stops execution and returns to the calling function. When a return statement is executed, the function is terminated immediately at that point, regardless of whether it's in the middle of a loop, etc.

Return optional in void functions

A void function doesn't have to have a return statement -- when the end is reached, it automatically returns. However, a void function may optionally contain one or more return statements.
void printChars(char c, int count) {
    for (int i=0; i<count; i++) {
       cout << c;
    }//end for
    return;  // Optional because it's a void function
}//end printChars

Return required in non-void functions

If a function returns a value, it must have a return statement that specifies the value to return. It's possible to have more than one return, but the (human) complexity of a function generally increases with more return statements. It's generally considered better style to have one return at the end, unless that increases the complexity.

The max function below requires one or more return statements because it returns an int value.

// Multiple return statements often increase complexity.
int max(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
}//end max
Here is a version of the max function that uses only one return statement by saving the result in a local variable. Some authors insist on only one return statement at the end of a function. Readable code is much more important than following such a fixed rule. The use of a single return probably improves the clarity of the max function slightly.
// Single return at end often improves readability.
int max(int a, int b) {
    int maxval;
    if (a > b) {
        maxval = a;
    } else {
        maxval = b;
    return maxval;
}//end max

Related pages