Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
A return statement gives a result back to the code that made the function call. It does not display that result. For absoluteValue(-4), the function returns 4, and the caller can choose what to do with that 4.
int absoluteValue(int x) {
if (x < 0) {
return -x;
}
return x;
}
int result = absoluteValue(-4); // result becomes 4
cout << result; // cout prints 4The function call absoluteValue(-4) produces a value that can be stored in result, passed to another expression, or sent to cout. The return statement supplies the value. The output statement performs the printing. These are separate jobs, even when you write them together.
cout << absoluteValue(-4);What happens when the caller executes cout << absoluteValue(-4)?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
When absoluteValue(-4) starts, its parameter x has the value -4. The boolean condition x < 0 is true, so the if statement executes return -x. The operator - changes -4 to 4, and that 4 is sent back to the caller. Execution does not continue to the next statement inside absoluteValue.
int absoluteValue(int x) {
if (x < 0) {
return -x; // x is -4, so this returns 4
}
return x; // not reached for absoluteValue(-4)
}The final return x is still needed for a call whose condition is false, such as a call using the same function with a non-negative value. For the call absoluteValue(-4), however, return -x ends the function before control can reach that line.
The word int in the declaration says that absoluteValue promises to return an integer. The expression -x is an integer expression because x is an int, so return -x supplies a result that fits the promise. The expression x in the other return statement is also an int and also fits.
int absoluteValue(int x) {
if (x < 0) {
return -x; // an int expression
}
return x; // an int expression
}Replace the placeholder in the negative branch so absoluteValue(-4) returns 4.
int absoluteValue(int x) {
if (x < 0) {
PLACEHOLDER
}
return x;
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
A function declared with a non-void return type must provide a value on every possible path. In absoluteValue, the true condition x < 0 reaches return -x, while a false condition skips the if body and reaches return x. Therefore both paths produce an int.
int absoluteValue(int x) {
if (x < 0) {
return -x; // true path returns an int
}
return x; // false path returns an int
}If you remove the final return x, a call with x = -4 can still use return -x, but a call whose condition is false reaches the end without an int result. The compiler can issue a diagnostic because the function does not keep its declared promise on every path. Keeping a return on each path also makes the function's control flow explicit.