# 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:

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?

You have attempted of activities on this page