Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use

Watch Operator Precedence

You can mix logical operators in statements as long as you understand the order in which the logical operators will be applied (precedence).

1.  The NOT operator (!) is applied first,
2.  then, the AND operator (&&),
3.  and finally the OR operator (||).

 

Consider this example:

dog_acceptable = (tan || black && long-eared)

This example illustrates why it is important to know the order in which logical operators are applied.  At first glance it may appear that the statement above would consider a dog to be acceptable if the dog is either tan or black and also long-eared.  But in reality, the statement above considers a tan dog with short little ears as an acceptable dog.  Remember, the AND operator is evaluated first and then the result of the AND operation is used for the OR operation.  The statement can be corrected with parentheses:

dog_acceptable = ((tan || black) && long-eared)

Now, parentheses are evaluated first.

 

 Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use