# Re: Optimizing a switch statement

From: Julie (julie_at_aol.com)
Date: 03/04/04

```Date: Wed, 03 Mar 2004 20:10:49 -0800

```

David Rubin wrote:
>
> Thomas Matthews wrote:
> > Hi,
> >
> > My son is writing a program to move a character. He is
> > using the numbers on the keypad to indicate the direction
> > of movement:
> > 7 8 9
> > 4 5 6
> > 1 2 3
> > Each number has a direction except for '5'. So in
> > his switch statement, he omits a case for '5':
> > /* char direction; */
> > switch (direction)
> > {
> > case '1':
> > move_lower_left();
> > break;
> > case '2':
> > move_down();
> > break;
> > case '3':
> > move_lower_right();
> > break;
> > case '4':
> > move_left();
> > break;
> > case '6':
> > move_right();
> > break;
> > case '7':
> > move_upper_left();
> > break;
> > case '8':
> > move_up();
> > break;
> > case '9':
> > move_upper_right();
> > break;
> > } /* end switch direction */
> >
> > The case selectors are not contiguous in the above
> > example, since case '5' is omitted (on purpose).
> >
> > My question is: Would adding a case for '5' reduce
> > the code space and execution time for this switch
> > statement?
>
> A better solution is to use a lookup table of function pointers:
>
> typedef void (*dfunc)(void);
> dfunc move[] = {
> 0,
> move_lower_left,
> move_down,
> /* ... */
> move_upper_right,
> };
>
> and then
>
> int d;
> dfunc *f;
>
> while(d=getdirection()){
> if(f=move[d]){
> f();
> }
> };
>
> /david
>

That's what I was thinking. But you can even optimize away the if() by
creating a null function for the '5', something like:

void do_nothing(void) { }

dfunc move[] = {
do_nothing,
move_lower_left,
//...

while(d=getdirection()){
move[d]();
};