This Question is Possibly Answered

1 "correct" answer available (4 pts) 2 "helpful" answers available (2 pts)
123 Views 1 Replies Last post: Mar 11, 2010 2:53 AM by FrankL RSS
stowoda Newbie 77 posts since
Mar 6, 2009
Currently Being Moderated

Mar 11, 2010 1:54 AM

switch case & look up table

In my application I have a large piece of code which is a switch case directive.

It looks like this:

switch(a)
{
     case 1 :
     {
          switch(b)
          {
               case 1 :
               {
                    switch(c)
                    {
                         case 1 : {d=123;e=456;f=789};
                         break;
                         case 2 : {};
                         break;
                         case 3 : {};
                         break;
                         default:break;
                    }
               }break;
               case 2 :
               {
                    switch(c)
                    {
                         case 1 : {};
                         break;
                         case 2 : {};
                         break;
                         case 3 : {};
                         break;
                         default:break;
                    }
               }break;
               ..
               ..
               ..
               ..
               ..
               ..
               ..          }     }break;
     case 2 : 
     {
          ..
          ..
          ..
          ..

     }break;
     ..
     ..
     ..
     ..
     ..
     ..
}

Is it possible to wirte that code more space efficient? It doesnt have to be fast. Could I use a look up table?

What I must add is that the length or depth of each switch directive is not equal.

 

Hope You could follow..

FrankL Apprentice 1,100 posts since
Mar 16, 2009
Currently Being Moderated
Mar 11, 2010 2:53 AM in response to: stowoda
Re: switch case & look up table

If your compiler is clever, and your case values start with "0" or "1" and are a consecutive numbers, then your compiler will translate the switch-case to a jump via a table of pointers to the different cases with the case value as index.

In C it would look like

 

typedef void (* function_ptr_t)(void);

function_ptr_t Case1Destinations[]={Case1_entry, Case2_entry, Case3_entry};

 

and you can call it like

     Case1Destinations[a]();

 

With the nested switch-cases you can of yause also do a multi-dimensinal array with one dimension for each switch.

But it would be best if you write separate functions for each case handling routine.

More Like This

  • Retrieving data ...

Bookmarked By (0)