Re: Optimizing a switch statement

From: CBFalconer (cbfalconer_at_yahoo.com)
Date: 03/05/04


Date: Fri, 05 Mar 2004 20:20:21 GMT

Thomas Matthews wrote:
>
> 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)
> {
... snip coding ...
> } /* 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?
>
... snip ...
>
> {I cross posted to the three newsgroups because
> this issue deals with a switch statement which
> exists in both the C and C++ languages. This
> may also be of interest to newbies, like my son.}

My version, possibly creating less code, but pointless otherwise:

         switch (direction) {
case 1: x--;
case 2: y++; break;
case 3: y++;
case 6: x++; break;
case 7: y--;
case 4: x--; break;
case 9: x++;
case 8: y--;
default: break;
         }

-- 
Chuck F (cbfalconer@yahoo.com) (cbfalconer@worldnet.att.net)
   Available for consulting/temporary embedded and systems.
   <http://cbfalconer.home.att.net>  USE worldnet address!


Relevant Pages

  • Re: Optimizing a switch statement
    ... > My son is writing a program to move a character. ... > his switch statement, he omits a case for '5': ... snip coding ... ... > the code space and execution time for this switch ...
    (comp.lang.cpp)
  • Re: Optimizing a switch statement
    ... > My son is writing a program to move a character. ... > his switch statement, he omits a case for '5': ... snip coding ... ... > the code space and execution time for this switch ...
    (alt.comp.lang.learn.c-cpp)
  • Optimizing a switch statement
    ... My son is writing a program to move a character. ... his switch statement, he omits a case for '5': ... C++ Faq: http://www.parashift.com/c++-faq-lite ... http://www.josuttis.com -- C++ STL Library book ...
    (alt.comp.lang.learn.c-cpp)
  • Optimizing a switch statement
    ... My son is writing a program to move a character. ... his switch statement, he omits a case for '5': ... C++ Faq: http://www.parashift.com/c++-faq-lite ... http://www.josuttis.com -- C++ STL Library book ...
    (comp.lang.cpp)
  • Optimizing a switch statement
    ... My son is writing a program to move a character. ... his switch statement, he omits a case for '5': ... C++ Faq: http://www.parashift.com/c++-faq-lite ... http://www.josuttis.com -- C++ STL Library book ...
    (comp.lang.c)