Programming in C

(Barry) #1

72 Chapter 6 Making Decisions


Program 6.4 Output (Rerun)
Enter your number to be tested: 6551
The number is odd.

Remember that the double equal sign ==is the equality test and the single equal sign is
the assignment operator. It can lead to lots of headaches if you forget this and inadver-
tently use the assignment operator inside the ifstatement.

Compound Relational Tests


The ifstatements that you’ve used so far in this chapter set up simple relational tests
between two numbers. In Program 6.1, you compared the value of numberagainst 0 ,
whereas in Program 6.2, you compared the value of gradeagainst 65. Sometimes, it
becomes desirable, if not necessary, to set up more sophisticated tests. Suppose, for exam-
ple, that in Program 6.2 you want to count not the number of failing grades, but instead
the number of grades that are between 70 and 79, inclusive. In such a case, you do not
merely want to compare the value of gradeagainst one limit, but against the two limits
70 and 79 to make certain that it falls within the specified range.
The C language provides the mechanisms necessary to perform these types of com-
pound relational tests. A compound relational testis simply one or more simple relational
tests joined by either the logical ANDor the logical ORoperator.These operators are rep-
resented by the character pairs &&and ||(two vertical bar characters), respectively. As an
example, the C statement
if ( grade >= 70 && grade <= 79 )
++grades_70_to_79;
increments the value of grades_70_to_79only if the value of gradeis greater than or
equal to 70 andless than or equal to 79. In a like manner, the statement
if ( index < 0 || index > 99 )
printf ("Error - index out of range\n");
causes execution of the printfstatement if indexis less than 0 orgreater than 99.
The compound operators can be used to form extremely complex expressions in C.
The C language grants the programmer ultimate flexibility in forming expressions.This
flexibility is a capability that is often abused. Simpler expressions are almost always easier
to read and debug.
When forming compound relational expressions, liberally use parentheses to aid read-
ability of the expression and to avoid getting into trouble because of a mistaken assump-
tion about the precedence of the operators in the expression.You can also use blank
spaces to aid in the expression’s readability. An extra blank space around the &&and ||
operators visually sets these operators apart from the expressions that are being joined by
these operators.
Free download pdf