HP C A.06.05 Reference Manual
Expressions and Operators
Logical Operators (&&, ||, !)
Chapter 5 115
Side Effects in Logical Expressions
Logical operators (and the conditional and comma operators) are the only operators for which
the order of evaluation of the operands is deļ¬ned. For these operators, operands must be
evaluated from left to right. However, the system evaluates only as much of a logical
expression as it needs to determine the result. In many cases, this means that the system
does not need to evaluate the entire expression. For instance, consider the following
expression:
if ((a < b) && (c == d))
The system begins by evaluating (a < b). If a is not less than b, the system knows that the
entire expression is false, so it will not evaluate (c == d). This can cause problems if some of
the expressions contain side effects:
if ((a < b) && (c == d++))
In this case, d is only incremented when a is less than b. This may or may not be what the
programmer intended. In general, you should avoid using side effect operators in logical
expressions.
j < m && n < m (j < m) && (n < m) 1
m + n || ! j (m + n) || (!j) 1
x * 5 && 5 || m / n ((x * 5) && 5) || (m / n) 1
j <= 10 && x >= 1 && m ((j <= 10) && (x >= 1)) && m 1
!x || !n || m+n ((!x) || (!n)) || (m+n) 0
x * y < j + m || n ((x * y) < (j + m)) || n 1
(x > y) + !j || n++ ((x > y) + (!j)) || (n++) 1
(j || m) + (x || ++n) (j || m) + (x || (++n)) 2
Table 5-11 Examples of Expressions Using the Logical Operators
Given the following declarations:
int j = 0, m = 1, n = -1;
float x = 2.5, y = 0.0;
Expression Equivalent Expression Result