C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

12. Juggling Several Choices with Logical Operators


In This Chapter


  • Getting logical

  • Avoiding the negative

  • The order of logical operators


Sometimes the relational operators described in Chapter 11, “The Fork in the Road—Testing Data to
Pick a Path,” simply can’t express all the testing conditions. For example, if you wanted to test
whether a numeric or character variable is within a certain range, you would have to use two if
statements, like this:


Click here to view code image


if (age >= 21) /* See if 21 <= age <= 65 */
{ if (age <= 65)
{
printf("The age falls between 21 and 65.\n");
}
}

Although there’s nothing wrong with using nested if statements, they’re not extremely
straightforward, and their logic is slightly more complex than you really need. By using the logical
operators you’ll read about in this chapter, you can combine more than one relational test in a single
if statement to clarify your code.


Note

Don’t let the terms logical and relational make you think these two groups of operators
are difficult. As long as you understand how the individual operators work, you don’t
have to keep track of what they’re called as a group.

Note

A relational operator simply tests how two values relate (how they compare to each
other). The logical operators combine relational operators.

Getting Logical


Three logical operators exist (see Table 12.1). Sometimes logical operators are known as compound
relational operators because they let you combine more than one relational operator. (See the

Free download pdf