Loading...

C++ Return Values

The parameters page ended with forty-four lines on the screen, and the last one was tag, the argument printed by show_label. This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. The empty announce function and the show_label function stay above main. This page continues the Functions module. The new work adds a function that sends a value back to the caller. That send uses the keyword return inside the body. main stores the result and prints it. The screen grows to forty-five lines, and the last one is 4.
A void function does work and sends nothing back. A function with a return type builds a value and hands it to the line that called it. You write the return type before the function name. Inside the body, return followed by a value ends the function and delivers that value. At the call, you can store what came back in a box, then print that box.
Programs return values all the time. A doubled count is computed once and used later. A status code tells the caller what happened. This page keeps the example as a small int calculation, so you can see the return type, the return line, and the stored result without new containers. The earlier void functions still run in the same file, so you can compare a function that only prints with a function that hands a number back to main.

The new definition sits above main with the other functions. The line int double_count(int n) begins it. The word int before the name is the return type: this function sends an int back. Inside the parentheses, int n is the parameter, the same idea as on the parameters page. The braces hold the body. The body has one job on this page: return n * 2;. That line multiplies n by 2 and sends the product back to the caller.
The call sits inside main after show_label("tag"); and before return 0;. First main stores the result: int doubled = double_count(count);. The box count already holds 2 from earlier in the file, so n receives 2, and the function returns 4. Then main prints that box with std::cout << doubled << std::endl;. The earlier lines still end with call and tag. The new last line is 4.
Walk the new ending. announce(); prints call. show_label("tag"); prints tag. double_count(count) returns 4 into doubled. The print shows 4. One new line appears. The first forty-four lines match the parameters page. The forty-fifth line is 4. The parameter name n inside double_count is not the same box as the loop counter n later in main; each lives in its own scope.

The return type in the header must match the value after return. Here both are int. Writing void double_count and then return n * 2; is the wrong shape, because void means nothing comes back. Forgetting return in a non-void function is also wrong for this page’s teaching shape. The return 0; at the end of main is different work: it ends main and reports success to the system. The return n * 2; inside double_count sends a calculated value to the caller.
A common mistake is to call double_count(count); and never store or print the result, so the screen does not show the new 4. Another common mistake is to print n inside main, but n exists only inside double_count. main uses doubled, the box that received the returned value.
This page stops before the next tool that lets one name hold more than one function shape. The next page names that tool once at the end. Here one name, double_count, has one parameter list and one return type.

Type the file in this order, or add only the new lines if types.cpp is already on disk. Above int main(), keep announce and show_label, and add double_count with its int return type, its int n parameter, and return n * 2;. Near the end of main, after show_label("tag"); and before return 0;, add int doubled = double_count(count); and the print line for doubled. The file name on disk stays types.cpp. The checked file is below, and the new lines are the double_count definition and the store-and-print in main.

types.cpp adds double_count that returns n * 2 and prints the result after show_label

cpp
#include <iostream>
#include <string>

void announce()
{
    std::cout << "call" << std::endl;
}

void show_label(std::string label)
{
    std::cout << label << std::endl;
}

int double_count(int n)
{
    return n * 2;
}

int main()
{
    // the word stays pine
    std::string word = "pine";
    int count = 2;
    double ratio = 0.5;
    bool ready = true;
    double price = 7.9;
    const int limit = 10;
    int scores[3] = {4, 5, 6};
    std::string other = "cone";
    std::string joined = word + " " + other;
    int total = 17;
    int step = 3;
    step += 4;
    int score = 72;
    int goal = 50;
    bool wet = false;
    std::string result;
    int day = 3;
    std::string name;
    std::cout << word << std::endl;
    std::cout << count << std::endl;
    std::cout << ratio << std::endl;
    std::cout << ready << std::endl;
    std::cout << word.size() << std::endl;
    std::cout << joined << std::endl;
    std::cout << word[0] << std::endl;
    std::cout << joined.find("cone") << std::endl;
    std::cout << joined.substr(5, 4) << std::endl;
    std::cout << count * 4 << std::endl;
    std::cout << 7 / 2 << std::endl;
    std::cout << 7.0 / 2 << std::endl;
    std::cout << (count > 1) << std::endl;
    std::cout << (count == 3) << std::endl;
    std::cout << !ready << std::endl;
    std::cout << static_cast<int>(price) << std::endl;
    std::cout << static_cast<double>(count) / 4 << std::endl;
    std::cout << static_cast<int>(ratio * 3) << std::endl;
    std::cout << limit << std::endl;
    std::cout << limit * count << std::endl;
    std::cout << scores[0] << std::endl;
    std::cout << scores[2] << std::endl;
    std::cout << total % 5 << std::endl;
    std::cout << step << std::endl;
    std::cout << (score >= goal) << std::endl;
    std::cout << (score < goal) << std::endl;
    std::cout << ((score >= goal) && (count == 2)) << std::endl;
    std::cout << ((score < goal) || wet) << std::endl;
    if (score >= goal) {
        result = "pass";
    } else {
        result = "retry";
    }
    std::cout << result << std::endl;
    if (wet) {
        std::cout << "wet" << std::endl;
    }
    switch (day) {
        case 1:
            name = "mon";
            break;
        case 2:
            name = "tue";
            break;
        case 3:
            name = "wed";
            break;
        default:
            name = "other";
            break;
    }
    std::cout << name << std::endl;
    for (int i = 0; i < 3; i++) {
        std::cout << i << std::endl;
    }
    int n = 3;
    while (n > 0) {
        std::cout << n << std::endl;
        n--;
    }
    for (int k = 0; k < 5; k++) {
        if (k == 2) {
            continue;
        }
        if (k == 4) {
            break;
        }
        std::cout << k << std::endl;
    }
    for (int value : scores) {
        std::cout << value << std::endl;
    }
    announce();
    show_label("tag");
    int doubled = double_count(count);
    std::cout << doubled << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 types.cpp -o types, then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows forty-five lines. The first forty-four are the same as on the parameters page. The last line is 4, the value returned from double_count when count holds 2.
Check the last three lines first. They should be call, then tag, then 4. The table gives each row its piece, so compare your run with it line by line. If the screen still ends with tag, the store-and-print for doubled is missing or sits after return 0;. If the build fails about void and return, the header still says void instead of int. If the last line is 2, you printed count instead of doubled.

📊 The double_count return and what it shows

Piece What the screen shows
First call, because announce still runs first among the function calls
Last 4, because double_count returns count * 2 and main prints doubled
Rule a non-void function uses return to send a value back to the caller
Screen pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, 20, 4, 6, 2, 7, 1, 0, 1, 0, pass, wed, 0, 1, 2, 3, 2, 1, 0, 1, 3, 4, 5, 6, call, tag, 4

Try one change at a time. Change return n * 2; to return n * 3;, leave the call as it is, and rebuild. The last line becomes 6, because 2 times 3 is 6. Put n * 2 back. Next, change the call to int doubled = double_count(5);, leave the body as it is, and rebuild. The last line becomes 10, because 5 times 2 is 10. Put double_count(count) back. Each experiment changes one thing, so the screen shows exactly which part caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
This page ends the return-value tool and stops before the next one. The next page is overloading, which lets one function name hold more than one parameter list. The double_count you have just written has one shape only. You leave with forty-five lines on the screen, and the last one is 4. Count the lines before you leave. There are forty-five, and the last one is 4.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top