title: Assembly Jump/Branch/Lookup Tables instead of lots of cmp/je?
body: <p>I've just started learning assembly and am making a simple boot loader as part of my OS class. I'm trying to make my code a little more efficient, i.e. I don't think what I've done so far is a particularly good way of achieving what I want. That said, I've been struggling to find any resources online that document a jump/branch/lookup table which I believe would be the most efficient way of doing this.</p>
  
  <p>To explain what I'm trying to achieve, I'm calling a function which returns a value in the <code>dx</code> register, from 0 to 4. Currently I'm using <code>cmp</code> instructions one after the other to compare the value and make a conditional <code>je</code> jump if the value is the same. If I had written this in a higher level language, I'd essentially be doing multiple <code>if</code> statements one after the other rather than using a more efficient <code>switch</code> statement.</p>
  
  <p>So here's what I'm doing right now:</p>
  
  <pre><code>cmp dx, 1          
  je .F_1
  cmp dx, 2
  je .F_2
  cmp dx, 3
  je .F_3
  cmp dx, 4
  je .F_4
  cmp dx, 0
  je .F_5
  jmp RangeError_Handler
  
  .F1:
    mov   si, msg1
    jmp   F_Exit
  .F2:
    mov   si, msg2
    jmp   F_Exit
  ...  ; .F3 and .F4 follow the pattern
  
  .F5:             ; special case
    mov   si, msg_error
    call  PrintLn
    hlt
  
  F_Exit:
    call  PrintLn
    ...            ; and do something else
  
  
  msg1: db 'Message 1', 0
  msg2: ...
  ...
  </code></pre>
  
  <p>There has to be a better way to do this. My tutor hinted that the jump table would be ideal but didn't have time to give me any kind of further explanation as to how that might work in assembly so I'd be extremely grateful if someone could provide some sort of example in the context of my situation.</p>
  
  <p>Theoretically, I'd have one function that checked the value of dx and then jumped to a particular function rather than checking 5 separate times, I just can't see how I would implement that in assembly. Would it be more efficient to use a lookup table for the strings also? i.e. a return value of 1 would indicate string 1 in the table?</p>