CS-220, Week 5C
R. Eckert
EMULATING HIGH LEVEL LANGUAGE CONTROL STRUCTURES IN ASSEMBLY LANGUAGE
I. IF-THEN-ELSE:
We want to implememnt the an equivalent to the following in
assembly language:
if <condition>
{Then Block}
else
{Else Block}
IF-THEN-ELSE Flow chart:
<Test the>
--------<condition>--------
| TRUE FALSE |
| |
Then Block Else Block
Statements Statements
| |
| |
---------->(DONE)<---------
Assembly language emulation--
Test Condition (CMP)
J<ConditionTrue> THEN
Else Statements... ;this is the else block
go here
JMP DONE
THEN: Then Statements... ;this is the then block
go here
DONE:
Example--The following is high level language pseudo-code:
if AX > BX
then
mov AX into BIG
else
mov BX into BIG
Now the assembly language equivalent:
CMP AX,BX
JG THEN1
MOV BIG,BX ;this is the else clause
JMP DONE1
THEN1: MOV BIG,AX ;this is the then clause
DONE1:
II. COUNTING LOOPS:
We want to emulate the following (C code given)--
&
nbsp;
for(COUNT=1; COUNT<=N; COUNT++)
{Body of loop}
One way to emulate this is to use a down counter.
Counting Loop Flow Chart:
COUNT <-- N
|<-------------
Body of Loop |
| |
COUNT <-- COUNT - 1 |
| |
<COUNT == 0?> -------
yes | no
|
In assembly language let's use CX as the down counter:
MOV CX,N
AGAIN: Statements that...
make up the body...
of the loop
DEC CX
JNZ AGAIN
In the case of the 80X86, the instruction LOOP has the effect of the
last two instructions. (This only works if the counter is CX register.)
Example--Compute X^N. We'll use AX to hold the result.
MOV AX,1 ;initialize
MOV CX,N ;loop counter
TOP: MUL X
LOOP TOP
III. WHILE LOOPS:
We want to emulate the following--
while <condition>
{Body of loop}
Here the statements in the Body of the loop are repeated as long as the
condition is true.
While Loop Flow chart:
----------->|
| |
| <Test Condition>---------
| | FALSE |
| TRUE | |
| | |
| Body of Loop |
| | |
| | v
------------ (DONE)
We now emulate this in assembly language:
TOP: Test Condition
J<condition true> TRUE
JMP DONE
TRUE: Body of loop...
statements go here
JMP TOP
DONE:
Let's now use this while loop emulator to do the X^N problem that we
solved before using a counting loop.
"High Level" Language Pseudocode:
AX = 1
CX = 1
while (CX<=N)
{
AX = AX*X
CX = CX+1
}
Assembly language:
MOV AX,1
MOV CX,1
TOP1: CMP CX,N
JBE TRUE1
JMP DONE1
TRUE1: MUL AX,X ;This the body of the loop
INC CX
JMP TOP1
DONE1: