70 likes | 192 Views
Switch statements. Multi-way selection (more than two alternatives) Can handle as a series of two-way selections Slow when later cases execute Can do multi-way branching directly Jump table Sometimes more efficient A number of cases Small range. Section 6.4 Switch Statement.
E N D
Switch statements • Multi-way selection (more than two alternatives) • Can handle as a series of two-way selections • Slow when later cases execute • Can do multi-way branching directly • Jump table • Sometimes more efficient • A number of cases • Small range Comp Sci 251 -- switch
Section 6.4 Switch Statement Jump tables - arrays Comp Sci 251 -- switch
Jump table • Array of addresses (case labels) • Data definition: j_table: .word case0, case1, case2, case3 • Assumption: case0, case1, … are labels in .text segment Comp Sci 251 -- switch
Jump register instruction jr Rsrc • Jump to the address in Rsrc • First load jump table entry into register • (Also used to return from function call) Comp Sci 251 -- switch
switch(y){ case 0: x++; break; case 1: x--; break; case 2: x *= 2; break; } .text case0: lw $t0, x addi $t0, $t0, 1 sw $t0, x j endSwitch case1: lw $t0, x subi $t0, $t0, 1 sw $t0, x j endSwitch case2: lw $t0, x sll $t0, $t0, 1 sw $t0, x endSwitch: Switch example Comp Sci 251 -- switch
.data j_table: .word case0 .word case1 .word case2 .text lw $t0, y bltz $t0, endSwitch bgt $t0, 2, endSwitch # $t0 now contains 0, 1, or 2 sll $t0, $t0, 2 lw $t1, j_table($t0) jr $t1 case0: ... Switch example (continued) Comp Sci 251 -- switch
Switch Exercise Int result, x; Switch (x) { case 100: result *= 13; break; // No case 101 case 102: result +=10; // Fall through case 103: result += 11; break; case 104: // 104, 106 same case 106: result *= result; // No case 105 break; default: result = 0; } Comp Sci 251 -- switch