Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 4.6 The Return Statement

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:
Listing 4.6.1. 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 printLogarithm 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>.
Putting return 0; in your code ends your program. Let’s look back at a program from section 4.3. How would your answer change?

Checkpoint 4.6.1.

What will print?
#include <iostream>
using namespace std;

int main() {
  int x = 8;
  if (x > 8) {
    cout << "One! ";
  }
  if (x > 6) {
    cout << "Two! ";
  }
  if (x > 3) {
    cout << "Three!" << endl;
  }
  return 0;
}
  • One! Two! Three!
  • Take a look at the first conditional statement more closely.
  • Two! Three!
  • 8 is not greater than 8, so it doesn’t meet the first condition.
  • Three!
  • All of the following are "if" statements, with no return. There are no "else" statements.
  • Two!
  • All of the following are "if" statements, with no return. There are no "else" statements.
  • One!
  • Take a look at the first conditional statement more closely.

Checkpoint 4.6.2.

What will print?
#include <iostream>
using namespace std;

int main() {
  int x = 8;
  if (x > 8) {
    cout << "One! ";
    return 0;
  }
  if (x > 6) {
    cout << "Two! ";
    return 0;
  }
  if (x > 3) {
    cout << "Three!" << endl;
    return 0;
  }
  return 0;
}
  • One! Two! Three!
  • Try again! 8 is not greater than 8, so the first condition will not be met.
  • Two! Three!
  • Try again! Remember what "return 0" is for!
  • Three!
  • Try again! 8 is greater than 6!
  • Two!
  • Correct!
  • One!
  • Take a look at the first conditional statement more closely.
You have attempted 1 of 3 activities on this page.