GOOC - Game Oriented Object C

GOOC - Game Oriented Object C

Next: Bitwise Shift Operators, Previous: Comparison Operators, Up: Expressions and Operators
[Contents]

7.4. Logical Operators

7.4. Logical Operators

Logical operators test the truth value of a pair of operands. Any nonzero expression is considered true, while an expression that evaluates to zero is considered false.

The logical conjunction operator && tests if two expressions are both true, while the logical disjunction operator || tests if at least one of two expressions it true. if (foo == 4 && bar == 2) { // code to run when foo is equal to 4 and bar is equal to 2 } if (foo == 4 || bar == 2) { // code to run when foo is equal to 4 OR bar is equal to 2 }

You can prepend a logical expression with a negation operator ! to flip the truth value: if (!(foo < 0)) { // code to run if foo is not lower than zero, i.e. negative }

Unlike in C, the full logical expression is always evaluated, regardless of if the value is known to be either true or false at an earlier point in the evaluation.