Loading...

C++ Functions

The range-for page ended with forty-two lines on the screen, and the last one was 6, the final element printed from scores. This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. The loops stay in the file. The workshop example stays, but the module changes. Control Flow is finished. This page begins Functions. The new work packs one print into a named function above main, then calls that name from inside main. The screen grows to forty-three lines, and the last one is call.
Until now, every print sat directly inside main. A function lets you give a short name to a piece of work and run that work by writing the name with parentheses. The body of the function holds the statements. The call in main is the moment those statements run. On this page the function is named announce, it returns nothing, and its only job is to print the word call. The rest of the file still builds the same workshop screen you already know, so the only new ending is that one word.
Programs use functions to keep main short and to reuse the same steps later. A greeting can live in one place. A cleanup step can live in one place. You can call the same name twice when you need the same print again, without copying the print line by hand. This first page keeps the body tiny on purpose, so you can see the shape of the definition and the shape of the call without new tools mixed in. Parameters and return values wait for later pages in this module.

A function definition starts above main in this file. The line void announce() begins it. The word void means the function does not send a value back to the caller. The name announce is the label you will call. The empty parentheses mean this page does not pass any values in. The braces under that line hold the body. Inside the body sits one print: std::cout << "call" << std::endl;.
The call sits inside main, after the range-for and before return 0;. The call looks like announce();. The name must match the definition exactly, and the parentheses must be there even when they are empty. When main reaches that line, the program jumps into announce, runs the print, then returns to the next line in main, which is return 0;.
Walk the new part. main finishes the earlier prints, including 4, then 5, then 6 from the range-for. Then announce(); runs. The body prints call. One new line appears at the end of the screen. The earlier forty-two lines stay the same. Nothing inside announce reads the array or the loops; it only prints its own text. That separation is useful later, when the body grows, because you can change the message in one place and every call picks up the change.

The definition must appear before the call in this beginner shape, so the compiler has already seen announce when main uses it. Putting the whole function below main without a prior declaration is a later habit; this page keeps the function above main so one file reads top to bottom.
A common mistake is to write announce; without parentheses. That does not call the function. Another common mistake is to put the print only in main and never define announce, or to define announce and forget the call, so the new line never appears. The quotes around "call" are required, because call is text on this page, not a variable name.
This page stops before the next function tool that sends a value into the parentheses. The next page names that tool once at the end. Here the parentheses stay empty on purpose.

Type the file in this order, or add only the new lines if types.cpp is already on disk. Above int main(), add the announce function with its braces and the print of "call". Near the end of main, after the range-for and before return 0;, add announce();. The file name on disk stays types.cpp. The checked file is below, and the new lines are the function above main and the call inside main.

types.cpp adds void announce above main and calls it after the range-for

cpp
#include <iostream>
#include <string>

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

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();
    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-three lines. The first forty-two are the same as on the range-for page. The last line is call, the text printed inside announce.
Check the last line first. main reached announce();, the body ran, and "call" appeared. The table gives each row its piece, so compare your run with it line by line. If the screen still ends with 6, the call is missing or sits after return 0;. If the build fails with an unknown name, the definition above main is missing or the spelling does not match the call. If the last line is the word announce without quotes in the source, you printed a name instead of the text "call".

📊 The announce function and what it shows

Piece What the screen shows
First call, because announce runs once and prints that text
Last call, because that new line is the last line on the screen
Rule a void function holds work above main, and the call runs that work
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

Try one change at a time. Change "call" to "hi" inside announce, leave the call as it is, and rebuild. The last line becomes hi. Put "call" back. Next, write a second announce(); on the line above return 0;, leave the body as it is, and rebuild. The last two lines become call, then call, because the body runs once per call. Remove the second call. 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 first Functions tool and stops before the next one. The next page is parameters, which sends a value into the parentheses so the function can use that value inside its body. The empty announce you have just written is the right starting shape. You leave with forty-three lines on the screen, and the last one is call. Count the lines before you leave. There are forty-three, and the last one is call.

🧠 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