Tuesday, August 18, 2009

Logical operators

The conditional statements are often too complicated to be expressed by using only the relational operators. Logical operators can be used to combine conditions.

! !p Not (negation)
!p is true if p is false
&& p && q And (conjugation)
p && q is true if both p and q are true
|| p || q Or (disjunction)
p || q is true if either p or q is true


An important feature of the && || operators is that they, unlike arithmetic operators, do not always evaluate their second operand. The operands are evaluated one at a time from left to right and no more operands are evaluated when the result can be deducted. This is called short-circuit evaluation. One expression can be used to guard a potentially unsafe operation. For example: a possible division-by-zero:

int distance = 0;
int speed = 0;
int time = 0;
//...
if( speed != 0 && distance % speed == 0 )
{
     time = distance / speed;
}

where the short-circuit evaluation of && guarantees that an attempt to get the remainder from the division-by-zero or the division-by-zero never occur.


Previous post

Next post




No comments:

Post a Comment