4.1. Boolean Expressions¶
4.1.1. Relational and Logical Operators¶
Relational Operators
< > <= >=
Equality Operators
== !=
Logical Operators
! && ||
The main rule for order of precedence to note is that AND (&&) has higher
precedence than OR (||
). Other than this, they evaluate left to right as
expected.
a && b || c && d ---> (a && b) || (c && d)
(i<0)&&(j<0)||(i>=20)&&(j>=20) ---> ((i<0)&&(j<0)) || ((i>=20)&&(j>=20))
These logical expressions all evaluate to binary values of 0 or 1.
The unary operator NOT (!) reverses the result of the expression.
4.1.2. Short Circuit Evaluation¶
If the final result of an expression is determined after a portion of the expression is evaluated, the rest of the expression is skipped. Knowing this behavior can allow slightly more compact code.
if( (x != 0.0) && ((y = z/x) < 1.0) ) /* z/x never evaluated if( x == 0 ) */ if( (x < 0) || ((y = sqrt(x)) <= z )) /* sqrt(x) never evaluated if x < 0 */ if( (result == error) && exit(1) ); /* the same as `if( result == error ) exit(1); */
Note in the last example, we used an empty statement, the ‘;’ by it self as an expression. The empty statement can also be useful in writing control constructs.