4.7.分支,变量与迭代
\(4.7.\)Branching,Varables and Iteration
1.Branching
1 | //Computes:if R0>0 |
- Symbolic reference: The above code is correct but unreadable. Fortunately, we have a nice feature called symbolic reference. For example, the above code can be rewrited like this:
1 | @R0 |
The
POSITIVE
label appears twice in the code: In the first place we declare this label, and what we are saying is "here is a piece of code that I want to jump to some other place in the code calledPOSITIVE
".- LABEL translates to n, where n is the instruction number following the (LABEL) declaration, in the assembler.
2.Varables
In machine language, besides R0
and symbolic
reference, we can also set out own varables. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14@R0
D = M
@temp
M = D
@R1
D = M
@R0
M = D
@temp
D = M
@R1
M = D
The temp
is a varable set by ourselves, and we
represent it by using @temp
. This kind of naming improve
the readability of our code.
However, assembly language does not inherently support variables. Therefore, when we write "@temp", we are essentially requesting the computer to find an available memory register in the memory unit and assume its number to be "n", and then, from now on, use it to represent what we call the "variable temp".
3.Iteration
Considering this question: Compute RAM[1] = 1+2+...+RAM[0]. We have
the following pseudo code: 1
2
3
4
5
6
7
8
9
10n = RO
i = 1
sum = 0
LOOP:
if i>n goto STOP
sum = sum + i
i = i + 1
goto LOOP
STOP:
R1 = sum
We can implement the pseudo code as below: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40//initialize
@R0
D = M
@n
M = D
@i
M = 1
@sum
M = 0
//computing
(LOOP)
@i
D = M
@n
M = M - D
//the if clause
@STOP
D;JGT
@sum
D = M
@i
D = D + M
@sum
M = D
@i
M = M + 1
@LOOP
0;JMP
(STOP)
@sum
D = M
@R1
M = D
(END)
@END
0;JMP
We may take the process to lessen our burden with writing loop:
- First write in pseudo code.
- Debug your pseudo code.
- Translating the pseudo code into machine language.