4.7. Returning early

The return statement allows you to terminate the execution of a function before you reach the end. One reason to use it is if you detect an error condition:

This program will terminate with a return statement if the argument provided is not positive. Try running the code as is. If you get an error message, try changing the value of x.

This defines a function named print_logarithm that takes a double named x as a parameter. The first thing it does is check whether x is less than or equal to zero, in which case it displays an error message and then uses return to exit the function. The flow of execution immediately returns to the caller and the remaining lines of the function are not executed.

I used a floating-point value on the right side of the condition because there is a floating-point variable on the left.

Remember that any time you want to use one a function from the math library, you have to include the header file <cmath>.

Since main is the first function on the call stack, putting return 0; in your main ends your program.

Let’s look back at a program from the Chained Conditionals section. How would your answer change?

Compare Q1 to this example. Look it over carefully. At first glance it looks the same, but the logic is different.

Sometimes it is tempting to have multiple return statements, one in each branch of a conditional:

double absolute_value (double x) {
  if (x < 0) {
    return -x;
  }
  else {
    return x;
  }
}

Since these returns statements are in an alternative conditional, only one will be executed. Although it is legal to have more than one return statement in a function, you should keep in mind that as soon as one is executed, the function terminates without executing any subsequent statements.

Warning

If you put return statements inside of a chain of conditionals, then you have to guarantee that every possible path through the program hits a return statement. If you forget, your program will crash.

Code that appears after a return statement, or any place else where it can never be executed, is called dead code. Some compilers warn you if part of your code is dead.

Notice that there are two return statements in the code below. What if we pass zero as an argument, and neither conditional returns true?

This program is not correct because if x happens to be 0, then neither condition will be true and the function will end without hitting a return statement. Unfortunately, the program compiles and runs, but the return value when x == 0 could be anything, and will probably be different in different environments.

By now you are probably sick of seeing compiler errors, but as you gain more experience, you will realize that the only thing worse than getting a compiler error is not getting a compiler error when your program is wrong.

Here’s the kind of thing that’s likely to happen: you test absolute_value with several values of x and it seems to work correctly. Then you give your program to someone else and they run it in another environment. It fails in some mysterious way, and it takes days of debugging to discover that the problem is an incorrect implementation of absolute_value. If only the compiler had warned you!

From now on, if the compiler points out an error in your program, you should not blame the compiler. Rather, you should thank the compiler for finding your error and sparing you days of debugging. Some compilers have an option that tells them to be extra strict and report all the errors they can find. You should turn this option on all the time. The implementation below would fix the error in the code.

This code fixes the error in the previoius implementation of absolute_value. If we pass 0 as an argument, the function will return 0. Thus, every route through the conditonal is satisfied.

In almost all cases, when you see an else after a return the code can be simplified to eliminate the else block entirely:

The basic if-else construct appears so often in programming that C defines an operator for it – the ternary operator. The basic form is:

CONDITION ? TRUE_VALUE : FALSE_VALUE ;

It is called a ternary, because it is the only operator that is split into 3 parts. The ternary operator simplifies our function even further.

#include <iostream>

double absolute_value (double x) {
    return x < 0? -x : x;
}

int main () {
   std::cout << absolute_value(0);
   return 0;
}

As an aside, you should know that there is a function in the math library called fabs that calculates the absolute value of a double correctly.


More to Explore

You have attempted of activities on this page