Re: Optimizing a switch statement
From: CBFalconer (cbfalconer_at_yahoo.com)
Date: 03/05/04
- Next message: Mike Wahler: "Re: Increasing efficiency in C"
- Previous message: CBFalconer: "Re: NULL pointer (was Re: int/unsigned long * idiocy)"
- In reply to: Thomas Matthews: "Optimizing a switch statement"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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!
- Next message: Mike Wahler: "Re: Increasing efficiency in C"
- Previous message: CBFalconer: "Re: NULL pointer (was Re: int/unsigned long * idiocy)"
- In reply to: Thomas Matthews: "Optimizing a switch statement"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|