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 |
|
|
|
|
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.