1 / 7

Switch statements

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.

garnet
Download Presentation

Switch statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. Section 6.4 Switch Statement Jump tables - arrays Comp Sci 251 -- switch

  3. 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

  4. 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

  5. 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

  6. .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

  7. 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

More Related