# Example of switch statement converted into assembly, # from p. 129-130 in textbook. # # Purpose of registers: Here is original switch statement: # $s0 = variable f switch (k) { # $s1 = variable g case 0: f = i + j; break; # $s2 = variable h case 1: f = g + h; break; # $s3 = variable i case 2: f = g - h; break; # $s4 = variable j case 3: f = i - j; break; # $s5 = variable k } .data jump_table: .space 16 # 4 words = 16 bytes prompt: .asciiz "Enter a value of k for switch statement: " intro: .asciiz "The new value of f is " newline: .asciiz "\n" .text main: li $s1, 1 # Let's give initial values to registers li $s2, 2 li $s3, 10 li $s4, 20 li $t2, 4 # Book says we should have value 4 in $t2. # This is the overflow value for k, # since k must be in range 0..3 # Get value of k from the user li $v0, 4 # print a prompt la $a0, prompt syscall li $v0, 5 # get integer input syscall move $s5, $v0 # put user's input into $s5 (variable k) # Initialize jump table la $t4, jump_table la $t5, L0 sw $t5, 0($t4) # insert address of L0 at offset 0 la $t5, L1 sw $t5, 4($t4) # insert address of L1 at offset 4 la $t5, L2 sw $t5, 8($t4) # insert address of L2 at offset 8 la $t5, L3 sw $t5, 12($t4) # insert address of L3 at offset 12 # Now we begin the switch statement code: blt $s5, $zero, exit # Test if k < 0 bge $s5, $t2, exit # Test if k >= 4 add $t1, $s5, $s5 # Let $t1 = 4 * $s5 add $t1, $t1, $t1 # This gives offset for jump table add $t1, $t1, $t4 # add offset to base address lw $t0, 0($t1) # let $t0 = address to jump to jr $t0 # Now, jump to that address L0: add $s0, $s3, $s4 # case 0: f = i + j j exit # break L1: add $s0, $s1, $s2 # case 1: f = g + h j exit # break L2: sub $s0, $s1, $s2 # case 2: f = g - h j exit # break L3: sub $s0, $s3, $s4 # case 3: f = i - j exit: # Now, we are ready for the output: li $v0, 4 # print first part of sentence la $a0, intro syscall li $v0, 1 # print value of $s0 move $a0, $s0 syscall li $v0, 4 # print newline la $a0, newline syscall li $v0, 10 # end of program syscall