Page 295 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 295
272 Chapter 9 Implementation of C Procedures
Many else if expressions can be inserted between an if expression and the final
else expression. The branch instructions jump out of a statement that is executed to the
statement beyond the final else statement. Moreover, the final else expression may be
omitted. Obviously, one can have more than two OR or AND tests, and one can nest
OR tests within AND tests, or one can nest AND tests within OR tests, and so on.
One of the common errors in C is to confuse bit-wise logical OR with the OR test
discussed above. The expression if ((alpha < 5) | (beta == 0) ) gamma = 0;
encodes as
LDAA alpha ; get variable alpha
CMPA #5
BLT LO ; if greater or equal to 5
LDX #0 ; generate zero
BRA LI ; and skip
LO: LDX #1 ; otherwise generate one
LI: LDAA beta ; test variable beta
BEQ *+4 ; if nonzero, branch to middle of CPS
CLRB ; otherwise clear B
CPS #50689 ; address mode is actually LDAB #1
CLRA ; high-order byte is always zero
PSHX ; OR X into D
GRAB 1, SP ; by pushing X
ORAA 2, SP+ ; then pulling it and ORing it into D
TBEQ D, *+6 ; if the result is nonzero
CLR gamma ; clear variable gamma
What a difference a single character makes! Although the same answer is obtained with
the statement if ((alpha < 5) | j (beta ==0) ) gamma = 0; as with if ((alpha
< 5) | (beta == 0) ) gamma = 0;, the assembly language generated by the latter is
significantly less efficient than that generated by the former statement.
Another of the common errors in C is to confuse assignment with equality test. The
expression if (beta == 0) gamma = 0; encodes as
TST beta ; test variable beta
BNE *+5 ; if the result is nonzero then
CLR gamma ; clear variable gamma
The expression if (beta = 0) gamma = 0; encodes as
CLR beta ; clear variable beta (note: this is an assignment statement)
BNE *+5 ; if the result is nonzero (it isn't) then
CLR gamma ; clear variable gamma
From the rest of Figure 9.8, note how a string of else if (...).. . else . . . ;
statements cause the tests we have already discussed to be done, and when one is
successful, so its following statement is executed, a branch is made to the end of the
series of else if(.. . ) . . . else . . .; statements. Incidentally, the subroutine branched
tobyBSR * +10 2 shifts the byte in beta left three places.