In: Computer Science
A switch/case statement allows multiway branching based on the
value of an integer variable.
In the following example, the switch variables can assume one of
the three values in [0, 2] and a different action is specified for
each case.
switch (s) {
case 0: a=a+1; break;
case 1: a=a-1; break;
case 2: b=2*b; break;
}
Show how such a statement can be compiled into MiniMIPS assembly instructions.
Please up vote ,comment if any query . Thanks for question . Be safe .
Note : check attached image for register value after program ends . code compiled and tested in MARS mips .
Program :
#--------------------------------------------------------
#program to implement
switch case
#value of a variable in
$t0
#value of b variable in
$t1
#--------------------------------------------------------
.data
.text
main:
#value in $t0 using addi
addi $t0,$0,2 #$t0(a)=2+0
# in $t1 using addi
addi $t1,$0,3 #$t1(b)=3+0
#beq is a branch instruction
#beq <operand 1> <operand
2>,label
beq $t0,0,case0 #if $t0(a)==0 go to
case0 label
beq $t1,0,case1 #if $t0(a)==1 go to
case1 label
beq $t2,0,case2 #if $t0(a)==2 go to
case2 label
j exit #if a not equal to 0,1,2 go
to exit label (default break of switch)
case0:#case0 label
addi $t0,$t0,1 #$t0=$t0+1 =
a=a+1
j exit #break jump to exit
label
case1: #case1 label
addi $t0,$t0,-1 #$t0=$t0-1
#a=a-1
j exit #jump to exit label
case2: #case 2
mul $t1,$t1,2 #b=b*2
#t1=$t1*2
j exit #jump to exit label
exit: #exit label
li $v0,10#syscall 10 to exit
syscall
Output : when a=2 using switch b=3 so after switch case
b=6
Output : a=0 and b=1 than using switch a=a+1=1
Please up vote ,comment if any query .