Skip to content

Name a Useful Calculation

The Course
•
35 min study

Yesterday's goal checkpoint calculated "minutes still missing" inline, right where it printed. If the report, a progress bar and a test all need that number, you would write the same subtraction three times, and a fix to one copy would not reach the others. A function gives a calculation a name. You write it once, call it wherever you need it, and fix it in one place.

A function names an operation with inputs and a result. The return type comes first, followed by the function's name and its typed parameters in parentheses. A call such as remaining(60, 25) supplies arguments, which initialize the parameters. The return statement ends the function and sends a value back to the caller, and the call expression takes on that value.

Predict and run

Predict before running C++
#include <iostream>

int remaining(int goal, int done) {
    if (done >= goal) {
        return 0;
    }
    return goal - done;
}

int main() {
    std::cout << remaining(60, 25) << " " << remaining(60, 70) << "\n";
    return 0;
}
Check your prediction
Text
35 0

The second call never reaches goal - done. The first return ends the function immediately, so a reached or exceeded goal gives 0 rather than -10. That is the function's promise: it never reports negative time. Try remaining(60, 60) and explain why the boundary should also return zero.

Calculate, then print

A function that returns a value is more useful than one that prints it. The caller decides what to do with the result: print it, compare it, add it to something, or test it. A function that prints can only print.

One result, three uses C++
#include <iostream>

int total_minutes(int hours, int minutes) {
    return hours * 60 + minutes;
}

int main() {
    int morning = total_minutes(1, 15);
    int evening = total_minutes(0, 40);
    std::cout << "Morning: " << morning << "\n";
    std::cout << "Day: " << morning + evening << "\n";
    if (total_minutes(2, 0) > morning + evening) {
        std::cout << "Two hours is more\n";
    }
    return 0;
}
Text
Morning: 75
Day: 115
Two hours is more

total_minutes knows nothing about reports. The same function produced a printed value, a sum and a comparison. When a function needs no result, its return type is void, and it is called for its effect, such as printing.

Parameters are local copies

Each call creates fresh parameter variables, initialized from the arguments. hours and minutes above exist only while the call runs, and they are separate from any variables in main, even ones with the same name. When the function returns, its parameters and local variables are destroyed. Values flow in through parameters and out through return; there is no other connection between the two functions. The next lesson shows the one exception, a reference parameter, and why you should use it deliberately.

Declare before use, and always return

C++ reads a file from top to bottom. A call must come after the function is declared, so for now define helpers above main. If you call a function before the compiler has seen it, you get an error such as use of undeclared identifier 'remaining'.

A function with a non-void return type must return a value on every path. Here the path for a reached goal falls off the end:

C++
int remaining(int goal, int done) {
    if (done < goal) {
        return goal - done;
    }
    // no return here: undefined behavior if this path runs
}

Using the result of a call that ended without return is undefined behavior; the caller may receive any number at all. The compiler warns, and a local build with -Werror stops with the error below. The browser editor builds without warning flags, so there it may run and print any number:

Shell
main.cpp:6:1: error: non-void function does not return a value in all control paths [-Werror,-Wreturn-type]

Practice

Exercise

Your turn

Write int clamp_minutes(int minutes) that returns 1 for any value below 1, 180 for any value above 180, and the value itself otherwise. Call it from main with -5, 25 and 500 and print the three results on one line, 1 25 180. Then add calls for the edges 1 and 180 and predict their results.

Your workspace C++
#include <iostream>

// Define clamp_minutes here, above main.

int main() {
    // Call it three times and print the results.
    return 0;
}
Hint 1: the idea

There are three cases and each one returns. Handle the two out-of-range cases first, then return the unchanged value.

Hint 2: a first step

Start with if (minutes < 1) { return 1; }. Every path through the function must reach a return.

Show one solution
Run the solution C++
#include <iostream>

int clamp_minutes(int minutes) {
    if (minutes < 1) {
        return 1;
    }
    if (minutes > 180) {
        return 180;
    }
    return minutes;
}

int main() {
    std::cout << clamp_minutes(-5) << " " << clamp_minutes(25) << " "
              << clamp_minutes(500) << "\n";
    return 0;
}
Text
1 25 180

Each early return ends the call, so the final line only runs for values already known to be in range, and the compiler can see that every path returns. The edge values 1 and 180 pass through unchanged, which you can confirm by adding them. In the next lesson you will see when a function should change the caller's variable instead of returning a new value.

Was this article helpful?

Your response is saved on this device.