Re: Optimizing a switch statement
From: Greg Comeau (comeau_at_panix.com)
Date: 03/04/04
- Next message: David White: "Re: better understanding references"
- Previous message: thides: "Re: better understanding references"
- In reply to: Thomas Matthews: "Optimizing a switch statement"
- Next in thread: Thomas Matthews: "Re: Optimizing a switch statement"
- Reply: Thomas Matthews: "Re: Optimizing a switch statement"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 3 Mar 2004 23:42:21 -0500
In article <4046A691.1050904@sbcglobal.net>,
Thomas Matthews <Thomas_MatthewsSpamBotsSuck@sbcglobal.net> 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)
> {
> 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?
Maybe, maybe not.
>The logic behind this is that a contigous set of
>case selectors would allow the compiler to create
>a "jump table", where as the above example may
>force the compiler to generate an "if-elseif"
>ladder.
You don't know. And trying to second guess implementations
in this case seems to be programming at the wrong level.
Just to toss more wrenches in, there is also std::map's
and such as well as a good 'ol array of structs you can
build too.
-- Greg Comeau / Comeau C++ 4.3.3, for C++03 core language support Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90. Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
- Next message: David White: "Re: better understanding references"
- Previous message: thides: "Re: better understanding references"
- In reply to: Thomas Matthews: "Optimizing a switch statement"
- Next in thread: Thomas Matthews: "Re: Optimizing a switch statement"
- Reply: Thomas Matthews: "Re: Optimizing a switch statement"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|