# This is a simple version of the switch structure # # switch (k) { # case 0: f = i + x; break; /* k = 0 */ # case 1: f = g + h; break; /* k = 1 */ # case 2: f = g - h; break; /* k = 2 */ # case 3: f = i - x; break; /* k = 3 */ # } # ... ... # You can improve it in your practice # # Caution: Don't use j as variable in the code as it may cause an error due to naming conflict with the jump instruction j. # .data jumptable: .word 0 , 0 , 0 , 0 k: .word 1 # Instead of giving a hard-coded value, you can read k from keyborad for flexibility f: .word 0 g: .word 4 h: .word 3 i: .word 8 x: .word 7 mess: .asciiz "\n please input 0-3!\n" # Used as prompt message when reading k from keyborad for flexibility .text .globl main main: # Construct the jumptable la $t4, jumptable la $s6, L0 sw $s6, 0($t4) la $s6, L1 sw $s6, 4($t4) la $s6, L2 sw $s6, 8($t4) la $s6, L3 sw $s6, 12($t4) # Data transfer from memory to registers ... lw $s5, k lw $s4, x lw $s3, i lw $s2, h lw $s1, g lw $s0, f li $t2, 4 la $t4 jumptable # Input validation slt $t3, $s5, $zero bne $t3, $zero, exit slt $t3, $s5, $t2 beq $t3, $zero, exit # Address jumptable[k] add $t1, $s5, $s5 add $t1, $t1, $t1 add $t1, $t1, $t4 lw $t0, 0($t1) # jump to an address contained in a register jr $t0 L0: add $s0, $s3, $s4 j cal_rest # jump over the rest cases L1: add $s0, $s1, $s2 j cal_rest # jump over the rest cases L2: sub $s0, $s1, $s2 j cal_rest # jump over the rest cases L3: sub $s0, $s3, $s4 # One final step for the calculation cal_rest: li $v0 1 add $a0 $zero $s0 syscall li $v0 10 syscall exit: li $v0 4 la $a0 mess syscall li $v0 10 syscall