That’s a lot to decipher. Not only is the statement hard to read, but there is a subtle error. The || is
compared last (because || has lower precedence than &&), but that || should take place before the
second &&. (If this is getting confusing, you’re right! Long-combined relational tests often are.) Here,
in spoken language, is how the previous if operates without separating its pieces with proper
parentheses:
If the student’s grade is more than 93 and the student missed three or fewer classes and the school
activities total three or more, OR if the student participated in two or more sports...
Well, the problem is that the student only has to be in sports activities to get the reward. The last two
relations (separated with the ||) must be compared before the third &&. The spoken description
should read like this:
If the student’s grade is more than 93 and the student missed three or fewer classes and EITHER
the school activities total three or more OR the student participated in two or more sports...
The following if, with correct parentheses, not only makes the if accurate, but also makes it a little
more clear:
Click here to view code image
if ((grade > 93) && (classMissed <= 3) && ((numActs >= 3) || (sports
>= 2)) {
If you like, you can break such long if statements into two or more lines, like this:
Click here to view code image
if ((grade > 93) && (classMissed <= 3) &&
((numActs >= 3) || (sports >= 2)) {
Some C programmers even find that two if statements are clearer than four relational tests, such as
these statements:
Click here to view code image
if ((grade > 93) && (classMissed <= 3)
{ if ((numActs >= 3) || (sports >= 2))
{ /* Reward the student */ }
The style you end up with depends mostly on what you like best, what you are the most comfortable
with, and what appears to be the most maintainable.
The Absolute Minimum
This chapter’s goal was to teach you the logical operators. Although relational
operators test data, the logical operators, && and ||, let you combine more than one
relational test into a single statement and execute code accordingly. Key concepts from
this chapter include:
- Use logical operators to connect relational operators.
- Use && when both sides of the operator have to be true for the entire condition to be
true. - Use || when either one side or the other side (or both) have to be true for the entire
condition to be true.