Loading...

C++ if and else

The logical page ended with twenty-eight lines on the screen, and the last two were 1 and 0, the answers to ((score >= goal) && (count == 2)) and ((score < goal) || wet). This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. Every line on the screen so far has printed a value that the code computed. From this page on, the program can choose which lines run, so the screen grows to twenty-nine lines in a new way.
This page starts the Control Flow module. Control flow is the part of a program that decides what runs next. The tools in this module are if, else, switch, the loops, and the words that leave a loop early. The first of them is if, which runs a block of code only when a condition is true. The file keeps its name, and the new work adds a string box named result and a few lines at the end.
Programs make decisions all the time. A shop charges tax only when the buyer lives in the country. A game ends the level when the timer reaches zero. A login page shows an error when the password is wrong. Each of those decisions needs a yes or no answer, and the logical operators from the previous page give you the answer. The if statement is what turns that answer into a choice between two paths.

An if statement has a condition in parentheses and a block in braces. The condition is an expression that gives true or false, such as score >= goal from the comparison page. When the condition is true, the statements inside the braces run. When it is false, the statements inside the braces are skipped, and the program continues with the line after the closing brace. The braces group the statements that belong to the if, so the reader can see where the block starts and ends.
An else gives the second path. It follows the closing brace of the if block and has its own block in braces. The if and the else together make one statement, and exactly one of the two blocks runs each time the statement is reached. If the condition is true, the if block runs and the else block is skipped. If the condition is false, the else block runs and the if block is skipped. Neither block runs twice, and the program never runs both.
The new block in this file uses that rule. The condition score >= goal is true, because 72 is at least 50, so the program runs the if block and stores pass in the box result. The else block would store retry, but it is skipped. The string result is set in exactly one place, and the line that prints it runs after the choice is made. A string value is written in double quotes, the same way the earlier pages wrote the word pine.

An if can stand alone without an else. The new block at the end of the file is that kind of statement. Its condition is wet, which holds false, so its block is skipped and nothing is printed. That is why the screen does not gain a line from that block. A block that does nothing on the current values is still useful, because a later change to wet makes it run without any change to the structure of the program.
Always write braces, even when a block holds only one statement. Without braces, the statement after if is the only part that belongs to it, and the next line is easy to misread. Many bugs in C++ come from a block whose braces were left out, when a second line was added later and was not included in the if. The braces in this file also show the start and end of each block clearly, so the reader sees the shape of the choice at a glance.
Watch the difference between = and == inside a condition. The statement if (score = goal) does not ask a question. It copies 50 into score, and the value of that assignment is 50, which is not zero, so the condition counts as true. The program then runs the if block for the wrong reason, and the compiler does not stop the build. The correct form is if (score == goal), which asks whether the two values are the same. Read every condition slowly and check the operator before you run the file.

Type the file in this order, or add only the new lines if types.cpp is already on disk. Under the line bool wet = false;, add one string box: std::string result;. Before the line return 0;, add the if and else block, one print line for result, and the if block for wet. The checked file is below. The file name on disk stays types.cpp, and the new lines are the string box, the choice, the print line, and the block with the braces.

types.cpp adds a string box, an if and else choice, and an if block to the twenty-eight

cpp
#include <iostream>
#include <string>

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;
    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;
    }
    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 twenty-nine lines. The first twenty-eight are the same as on the logical page. The twenty-ninth line is result, which prints the word pass.
Check the twenty-ninth line first. The condition score >= goal is true, so the if block ran and stored pass in the box, and the screen shows pass. Then look for the block with wet. Its condition is false, so the block was skipped, and no line for it appears on the screen. The table gives each row its piece, so compare your run with it line by line. If the screen has thirty lines, check that the wet block was not run by mistake.

📊 The choice and what it shows

Piece What the screen shows
First pass, because score >= goal is true, so the if block runs
Last no line, because wet is false, so its block is skipped
Rule exactly one branch of an if and else runs, and a block runs only when its condition is true
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

Try one change at a time. Change int goal = 50; to int goal = 80;, and the twenty-ninth line becomes retry, because 72 is not at least 80, so the else block runs. Put the 50 back. Next, change bool wet = false; to bool wet = true;. Two things change. The twenty-eighth line becomes 1, because wet is now true, and the wet block runs and prints a new last line with the word wet. Put the false value back. Each experiment changes one thing, so the screen shows exactly which line caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
This page starts the Control Flow module and stops before the next choice tool. The next page is switch, which chooses one of several cases from a single value. The if and else you have just written choose between two paths, and a switch extends the idea to many paths. You leave with twenty-nine lines on the screen, and the last one is pass. Count the lines before you leave. There are twenty-nine, and the last one is pass.

🧠 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