Lesson 11: Relational and Logical Operators
These operators are crucial for decision-making (control flow).
Relational Operators
Relational operators compare two values and return a Boolean result (in C, 0 for False, non-zero, usually 1, for True).
| Operator | Description | Example |
|---|---|---|
== | Equality (Is equal to) | x == y |
!= | Inequality (Is not equal to) | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Warning: A common mistake is using a single equals sign (=) (assignment) instead of double equals (==) (comparison). This mistake often leads to bugs where the assignment itself returns a non-zero (True) value.
Logical Operators
Logical operators combine two or more relational expressions.
| Operator | Description | Example |
|---|---|---|
&& | Logical AND | (age > 18) && (is_citizen) (True if both are true) |
| ` | ` | |
! | Logical NOT | !(is_raining) (Reverses the Boolean value) |
Short-Circuit Evaluation
C uses short-circuit evaluation for && and ||:
- In
E1 && E2, if E1 is False (0), E2 is never evaluated. - In
E1 || E2, if E1 is True (non-zero), E2 is never evaluated. This optimizes performance and prevents side-effects in the second expression if the first determines the outcome.