Logical Operators
Lesson outline
Introduction to Logical Operators
Logical operators allow you to combine or modify boolean expressions. They are essential for building complex conditions in control structures such as if statements and loops (e.g., while, for).
C++ defines three main logical operators: AND (&&), OR (||), and NOT (!). Operands are evaluated in a boolean context (nonzero values convert to true; zero converts to false).
Logical Operators Table
| Operator | Name | Description | Example |
|---|---|---|---|
| && | Logical AND | True only if both operands are true | true && false → false |
| || | Logical OR | True if at least one operand is true | true || false → true |
| ! | Logical NOT | Reverses the boolean value | !true → false |
Truth Tables
Truth tables summarize the possible outcomes of logical operations:
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
Practical Examples
Short-Circuit Evaluation
C++ logical operators use short-circuit evaluation:
- For
&&, if the first operand is false, the second is not evaluated. - For
||, if the first operand is true, the second is not evaluated.
Operator Precedence & Grouping
Precedence (highest to lower among these): ! → && → ||.
Comparison operators (e.g., ==, <) are evaluated before logical &&/||. Use parentheses to make complex expressions explicit.
Do NOT Confuse with Bitwise Operators
Bitwise operators &, |, and ^ operate on individual bits and do not short-circuit. They also evaluate both operands. On boolean operands they yield boolean-like results but are usually not what you want for control flow.