7.6.分支

\(7.6.\)Branching

1.Branching implementation

  Take the following program as example:

1
2
3
4
5
6
7
8
9
10
11
12
//return x * y
int mult (int x, int y) {
int sum = 0;
int n = 1;

while !(n>y) {
sum += x;
n++;
}

return sum;
}

  This program can be translated into pseudo VM 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
function mult(x,y)
push 0
pop sum
push 1
pop n
label LOOP
push n
push y
gt
if-goto ENDLOOP
push sum
push x
add
pop sum
push n
push 1
add
pop n
goto LOOP
label ENDLOOP
push sum
return

  Notice that we have three new symbols: label, if-goto, goto:

  • label LABEL declare the label.
  • if-goto LABEL: if the statement is true, then jump to LABEL.
  • goto LABEL: jump to LABEL with no condition.

  With these three statement, we can translate the branching expression into VM code.