Page 249 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 249
226 Chapter 8 Programming in C and C++
8.3 Conditional and Loop Statements
Simple conditional expressions of the form if then (shown in Figure 8.la), full
conditionals of the form if then else (shown in Figure 8.1b), and extended conditionals
of the form if then else if then else if then . . . else (shown in Figure 8.lc), use
conditional expression operators (shown in Table 8.3). In the last expression, the else if
part can be repeated as many times as needed, and the last part can be an optional else.
Variables are compared using relational operators ( > and < ), and these are combined
using logical operators ( &&). For example, {a > 5) && (b < 7) is true if a > 5
andb < 7.
A useful alternative to the conditional statement is the case statement. (See Figure
8.2.) An expression giving a numerical value is compared to each of several possible
comparison values; the matching comparison value determines which statement will be
executed next. The case statement (Figure 8.2a) jumps into the statements just where the
variable matches the comparison value and executes all the statements below it. The
break statement can be used (as shown in Figure 8.2b) to exit the whole case statement
after a statement in it is executed, rather than executing the remainder of it.
Loop statements can be used to repeat a statement until a condition is met. A
statement within the loop statement will be executed repeatedly. The expressions in both
the following loop statements are exactly like the expressions of the conditional
statements, using operators as shown in Table 8.3.
Figure 8.1. Conditional Statements