C++ Logical Operators
The comparison page ended with twenty-six lines on the screen, and the last two were 1 and 0, the answers to (score >= goal) and (score < goal). This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. Each comparison on the screen answers one question. This page shows how to join several answers into one, so the new lines add two more answers and the screen grows to twenty-eight.
This page closes the Operators module. The last operators you meet here are the logical operators &&, ||, and !. They work on bool values, which means they take yes or no answers and give one yes or no answer back. You have already seen one of them on the screen. The line !ready has printed 0 on this screen for several pages, because ready is true and ! turns true into false.
Programs rarely ask only one question. A login checks that the password is right and the account is active. A game lets the player move when the door is open or the key is in the bag. A form accepts a number when it is above zero and below a limit. Each of those rules joins two answers, and the logical operators are the words the code uses for joining them.
The operator && means and. It gives true only when both sides are true. If either side is false, the result is false. The operator || means or. It gives true when at least one side is true, and it gives false only when both sides are false. The operator ! means not. It takes one bool and reverses it, so !ready is false when ready is true, and !wet is true when wet is false.
The first new line in this page uses &&. Its left side is (score >= goal), which is true because 72 is at least 50. Its right side is (count == 2), which is true because count holds 2. Both sides are true, so the whole expression is true, and cout prints 1. The second new line uses ||. Its left side is (score < goal), which is false, and its right side is wet, which is false. Both sides are false, so the whole expression is false, and cout prints 0.
A table of the possible answers helps when you are unsure. For &&, only the row where both sides are true gives true. For ||, only the row where both sides are false gives false. The three rows of || where one side or both sides are true give true. Writing the four rows out by hand, once, is a good way to check that you have the right operator for a rule.
The two operators have a rule that matters for speed and for safety. The compiler reads && from left to right, and once the left side is false, the answer is already false, so the right side is not checked at all. The operator || works the same way in reverse. Once the left side is true, the answer is already true, and the right side is skipped. This behavior is called short-circuit evaluation.
Short-circuit evaluation is useful when the right side would do something risky. Suppose a program has the array scores from the arrays page with three boxes, and it wants to read the box at position index only when that position exists. A line such as index < 3 && scores[index] > 0 reads the box only when index is less than 3. If index is 5, the left side is false, and the right side never reads past the end of the array. Writing the check in the other order would read the box first, and that read would be the bug the arrays page warned about.
Precedence decides how a long line is grouped when you do not add parentheses. The operator ! binds most tightly, then &&, then ||. So a line such as a || b && c means a || (b && c). Parentheses make the grouping visible to the reader, and every expression on this page uses them for that reason. Add parentheses whenever you mix && and || in one line, even when the grouping seems obvious to you.
Type the file in this order, or add only the new lines if types.cpp is already on disk. Under the line int goal = 50;, add one bool box: bool wet = false;. At the end of the writing lines, under the two comparison lines, add two logical lines: one for ((score >= goal) && (count == 2)) and one for ((score < goal) || wet). The file name on disk stays types.cpp. The checked file is below, and the new lines are the bool box and the two print lines at the end.
#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::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;
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-eight lines. The first twenty-six are the same as on the comparison page. The twenty-seventh line is ((score >= goal) && (count == 2)), which prints 1. The twenty-eighth line is ((score < goal) || wet), which prints 0.
Check the twenty-seventh line first. Both comparisons are true, so && gives true, and the screen shows 1. Then check the twenty-eighth line. Both sides of || are false, so the screen shows 0. The table gives each row its piece, so compare your run with it line by line. If the screen has more than twenty-eight lines, check that no print line was copied twice.
📊 Two logical lines and what they show
| Piece | What the screen shows |
|---|---|
| First | 1, both sides of && are true |
| Last | 0, both sides of |
| Rule | && needs both sides true, and |
| 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 |
Try one change at a time. Change count == 2 to count == 3, and the twenty-seventh line becomes 0, because the right side of && is now false. Put the 2 back. Next, change || wet to || ready, and the twenty-eighth line becomes 1, because ready is true and one true side is enough for ||. Put the line back to || wet. 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 closes the Operators module. The next page is if-else, which starts the Control Flow module. It uses the same yes or no answers you have just built, but it lets the program choose which lines run. You leave with twenty-eight lines on the screen, the last one 0. Count the lines before you leave. There are twenty-eight, and the last one is 0.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 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