Return to Unit Menu | | | Terms of Use  |

Operator Precedence

beware You need to be careful with logical operators.

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:

You want a dog that is either tan or black in color,
but that also has long ears.

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 (the dog you are looking for).  But in reality, the statement above also considers a tan dog with short little ears as an acceptable dog.  The statement is actually looking for a dog that is black with long ears OR a dog that is tan (with any kind of ears).

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 to choose the dog you want by using parentheses:

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

Now, parentheses are evaluated first.