Next: Summary
Up: Conditions
Previous: Logical Expressions
(i < 10) && (j > 0) ((x + y) <= 15) || (i == 5) !((i >= 10) || (j <= 0)) (i < 10) && 0
Note that in the last example an actual truth value ( 0 - false) was
used as one of the operands of &&
, this means that whatever the
value of i
this logical expression evaluates to false
(Why?). In these examples brackets have been used to make the order of
application of operators clear. However, in the main, they are not
strictly necessary if the precedence rules already considered for
arithmetic operators are extended to include relational and logical
operators. The consequent extended Operator Precedence Table
for C++ is:
highest - evaluate first () brackets ! + - logical not, unary plus, unary minus * / % multiply, divide, modulus + - add, subtract < <= > >= less than, less than or equal, greater than, greater than or equal == != equal, not equal && logical and || logical or = assignment lowest - evaluate lastBe careful not to confuse the assignment operator
=
with the logical
equality operator ==
.
Using this table with the following expression
x + y < 10 && x/y == 3 || z != 10
shows that the operators are evaluated in the order /
,
+
, <
, ==
, !=
,
&&
and ||
. This is equivalent to bracketting the
expression as follows:
((((x + y) < 10) && ((x/y) == 3)) || (z != 10))
Similarly the expressions written in bracketted form above could be written without brackets as:
i < 10 && j > 0 x + y <= 15 || i == 5 !(i >= 10 || j <= 0) i < 10 && 0
Now that logical expressions (or conditions) in C++ have been covered it is possible to move on and look at the conditional control structures in C++.