Logical and Arithmetic Operators

Friday, September 03, 2004

 

Logical Operators

Logical Operators

In more realistic examples, it is probably necessary to evaluate multiple conditions to determine what parts of code should execute. For instance, if condition 1 is true and condition 2 is true process one way, if condition 1 is true and condition two is false process another way.

C provides several logical operators that allow more complex relational expressions to be formed and evaluated.



















































Operator Description Example Evaluation




&& AND (5 > 1) && (3>10) False
&& AND (2 >1) && (10 > 9) True
|| OR (3> 1) || (10 > 11) True
|| OR (4> 2) || (10 > 5) True
! NOT !(5>1) False
! NOT !(2 > 3) True





As can be seen in this table, && will return true only if both expressions are true, while || will be true if either expression is true. The operator "!" provides logical negation. One very important consideration when forming expressions is the order of precedence (what is executed when) of the relational and logical operators.

Relational operators are of higher precedence (they are executed first) than the logical and the order of evaluation is from left to right. Here are some examples that illustrate what this means.

if (myChoice == 'A' and myAge < 25) is evaluated as

if ((myChoice == 'A') and (myAge < 25))

Suppose x = 8, y = 49, z = 1.

if (x < 7 && y > 50 || z < 2) is evaluated as


if (((x < 7) && (y > 50)) || (z < 2)) which is TRUE, not as

if ((x < 7) && ((y > 50) || (z < 2)) which is FALSE.



Now, here are a few final points to wrap up this. First, even if you are sure about the order of precedence of an expression, use many parenthesis (just in case). This serves to increase readability and will help avoid errors. Second, there is such a thing as green tea ice cream and I recommend that you not buy it.


Archives

September 2004  

This page is powered by Blogger. Isn't yours?