Page 1 of 1
Limits and effciency in switch / case structures
Posted: 20 Apr 2013, 01:17
by tabbycatrobots
My dancing robots are "learning" more and more steps (actions), and I use a switch / case structure while processing
their routines, to go to the code or function for each different step. In NXC, in a switch / case structure, is there
a limit on the number of cases? I may soon have over 100 cases. Even if there is not a limit, I'm thinking it may
be more efficient to use a 2 level construct. The first level switch / case will send the action_to_do to one of
three (dance step, comms, slave NXT), second level switch / case statements. Has anyone tried this? Thanks
for any thoughts / ideas.
Re: Limits and effciency in switch / case structures
Posted: 20 Apr 2013, 09:52
by HaWe
switch/case constants in C are nothing else than jump addresses constants.
I guess the upper limit would be sth like SHRT_MAX = 32767 (NXC 16 bit integer) (CMIIW)
I personally prefer if-then-else designes instead.
Re: Limits and effciency in switch / case structures
Posted: 21 Apr 2013, 02:33
by spillerrec
If the extended firmware still is as it used to be, switches are implemented a bit different from C. In C switches are usually converted to an array, where the case is used as an index, and the value is position to jump to. However the firmware doesn't support jumps based on variables, only constants. So the NXC compiler (at least used to) generated code like this iirc:
Code: Select all
if x then goto CASE_X;
if y then goto CASE_Y;
if z then goto CASE_Z;
...
CASE_X:
code; goto END; //This goto is what break; does
CASE_Y:
code; goto END;
CASE_Z:
code; goto END;
...
END:
There is quite a difference in complexity here. Using an array would give O( 1 ) while this construction would be O( n ) where n is the amount of cases. So in this case, using nested switches indeed would improve performance quite a bit.
The limits are, as doc said, dependent on how long it can jump, and that is more dependent on how much code you have in each case and not the amount of cases.
Re: Limits and effciency in switch / case structures
Posted: 22 Apr 2013, 00:25
by tabbycatrobots
Thanks for the explanations and ideas. It sounds like using a 2 level switch will gain me more than
I originally thought. Before adding more actions, I'll add the higher level switch. As the actions are
16 bit #defines, with the higher bits being the type of action, bit masks will make the top level
switch relatively easy to code.
Howard