The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
See also: Functions with Results | ||
![]() ![]() ![]() ![]() ![]() ![]() |
||
The Return Statement
void printLogarithm (double x) { if (x <= 0.0) { cout << "Positive numbers only, please." << endl; return; } double result = log (x); cout << "The log of x is " << result); } 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 math.h.
|
||
Home ![]() ![]() |