Jump table instead of Switch cases

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • srikky
    New Member
    • Aug 2012
    • 3

    Jump table instead of Switch cases

    Hi,

    I have an issue with switch case. There are about 32 cases to be handled in switch. each case just assigns a hexadecimal to a local variable.

    #define ADFV 0x0301

    Switch(error_in dex)
    {
    case 1:
    var = ADFV;
    ........

    }
    }
    can i use jump table for above issue to reduce the code size.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You could if you wanted but the fact is that a 32 case switch statment is pretty small and the change in the size of your executable will be miniscule. I don't think it's worth the effort.

    Comment

    • srikky
      New Member
      • Aug 2012
      • 3

      #3
      Thanks for your suggestion.

      Comment

      • srikky
        New Member
        • Aug 2012
        • 3

        #4
        Is it a good practice to use those many switch cases... is there any other better approach?

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          Can you count on the error_index values all being roughly between 0 and some maximum value -- with very few holes from unused error_index values? If so, then you could use a lookup table where each entry consists of a var value. Use error_index to index into the lookup table array.

          If error_index is not appropriate for use as an array index, then you could construct a lookup table where each entry has two fields: error_index and corresponding var. You could then replace the switch with a search-the-table snippet.

          Comment

          Working...