Logical operators evaluate the truth of a compound statement. The following table lists logical operators, with their corresponding default operator precedence. Operators with a numerically lower ranking are evaluated before operators with a numerically higher ranking, operators with the same ranking are evaluated left-to-right.
Operator | Description | Precedence Ranking |
---|---|---|
NOT | Logical NOT, negates the truth of the following conditional statement. | 1 |
~ | ||
AND | Logical AND, evaluates true if both preceding and following conditional statements are true. | 2 |
&& | ||
OR | Logical OR, evaluates true if either preceding or following conditional statements (or both) is true. | 3 |
|| |
Logical NOT (~)
A logical NOT (~) preceding a conditional statement inverts the truth of the conditional statement. It relates to the conditional statement itself, and is not the same as a relational NOT, which relates to the relational operator.
Examples
Example 1
This evaluates true if both expressions are true:
expression1 && expression2
Example 2
This evaluates true if at least one of the expressions is true:
expression1 || expression2
Example 3
This evaluates true if expression1 is true, but expression2 is false:
expression1 ~ expression2
Example 4
This evaluates true if expression1 is false:
~expression1