Next: Examples using logical operators Up: Conditions Previous: Examples using Relational Operators

Logical Expressions

It is possible to specify more complex conditions than those which can be written using only the relational operators described above. Since the value of a condition has a numerical interpretation it could be operated on by the usual arithmetic operators, this is not to be recommended. There are explicit logical operators for combining the logical values true and false.

The simplest logical operator is not which is represented in C++ by !. It operates on a single operand, and returns false if its operand is true and true if its operand is false.

The operator and, represented by &&, takes two operands and is true only if both of the operands are true. If either operand is false, the resulting value is false.

or is the final logical operator and is represented by ||. It results in true if either of its operands is true. It returns false only if both its operands are false.

The logical operators can be defined by truth tables as follows. Note that F is used for false and T is used for true in these tables.

Not ! And && Or ||
A !A A B A && B A B A || B
F T F F F F F F
T F F T F F T T
T F F T F T
T T T T T T

These tables show that not reverses the truth value of the operand, that the and of two operands is only true if both operands are true and that the or of two operands is true if either or both of its operands are true. Using these logical operators more complex conditions can now be written.

If i has the value 15, and j has the value 10, then the expression (i > 10) && (j > 0) is evaluated by evaluating the relation i > 10 (which is true), then evaluating the relation j > 0 (which is also true), to give true. If j has the value $-1$ then the second relation would be false, so the overall expression would be false. If i has the value 5, then the first relation would be false and the expression will be false irrespective of the value of the second relation. C++ does not even evaluate the second relation in this situation. Similarly, if the first relation is true in an or (||) expression then the second relation will not be evaluated. This short-circuit evaluation enables many logical expressions to be efficiently evaluated.



Next: Examples using logical operators Up: Conditions Previous: Examples using Relational Operators