Skip to content

Logical Expressions

Logical expressions are a fundamental part of control flow in C++. They evaluate to either true or false and are used to make decisions or repeat actions in your programs. By combining relational operators (e.g., ==, <, >) and logical operators (e.g., &&, ||, !), you can create complex conditions that determine how your code executes.

Relational operators compare two values and return a boolean result: true if the condition is met, or false if it is not. These operators are commonly used in logical expressions to make decisions or control loops.

OperatorMeaningExample
<less thanmy_variable < 10
>greater thanmy_variable > 10
<=less than or equal toi <= size
>=greater than or equal tovalue >= 1
==equalsvalue % 2 == 0
!=not equalschoice != "quit"

In C++, the primary logical operators are AND (&&), OR (||), and NOT (!). These operators are used to evaluate multiple conditions or invert a condition’s truth value, enabling more flexible and dynamic decision-making in your programs.

When you need to check for multiple conditions, use the AND operator:

x > 0 && x < 10

The OR operator is useful when meeting multiple conditions leads to the same result:

job == "web developer" || job == "frontend developer"

An example for when to use the NOT operator is when you are looking for falsy values:

(!a_true_value)

Truth tables are a simple way to visualize how logical operators evaluate conditions. They show all possible combinations of input values and the corresponding output for operators like AND, OR, and NOT.

The AND operator (&&) returns true only if both conditions are true. By looking at the truth table, you can see that if even one condition is false, the entire statement evaluates to false.

ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

The OR operator (||) returns true if at least one of the conditions is true. By examining the truth table, you can see that the statement evaluates to false only when both conditions are false.

ABA || B
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

The NOT operator (!) inverts the truth value of a condition. If the condition is true, applying the NOT operator makes it false, and vice versa.

A!A
truefalse
falsetrue