I've read through this thread: http://www.keil.com/forum/8020/
and I understand that: 1. For "a few" case values, I'll get a series of if / else if's. Not sure how many that is. 2. If the case values follow the format {0, 1, 2, ...}, I'll get a jump table. Sometimes. 3. Otherwise, I'll get a function call to the super-flexible library.
My problem is that I have a switch-based state machine that necessarily starts at 0xFF and uses a change in state as more of a yield() function in an RTOS. Something like this:
unsigned char state1; unsigned char state2; void main(void) { state1 = Read_Program_Memory(ADDR1); state2 = Read_Program_Memory(ADDR2); while(1) { if(state1) { thread1(); } thread2(); } } void thread1(void) { switch(state1) { case 0xFF: //do something //... state1 = 0xFE: case 0xFE: if(!condition_to_wait_for) { break; } //do some more //... //don't need to run this ever again state1 = 0x00: Write_Program_Memory(ADDR1, 0x00); } }
I really don't care what the case values are, but 0xFF has to be present for initialization and on top to make the first fall-through work. Is there a good, readable way to get a jump table out of this, so as to avoid the library call?
Thanks! Aaron
I bet you only read out the state information on startup of the program. So you could quickly there detect 0xff and convert to 0x00 as your "initial-start" value. Suddenly, you get a nice series of 0, 1, 2, 3, ... as case values.
But in the end, it's always meaningful to use labeled case values so you can quickly change their values and recompile and evaluate the outcome.
Or maybe 0x01 as the initial value and have a dummy 0x00 case to satisfy the compiler. I'd like to use 0x00 as the flag to not run it at all anymore.
Good point about the labeled case values. I knew that, but I got into a rush this time.
It's time for me to go home now, so I'll try it tomorrow. Thanks for the idea.
Yep, that worked.
I have a default case at the end for error checking, and it was okay with that. I took out the dummy case 0, and it was okay with that too.
So I guess all it cares about is increasing sequential.
Thanks for your help! Aaron
Sequential is good.
Using unsigned numbers and including zero is also good, even if the zero statement just contains a break.
Then the code need just check:
if (idx >= COUNT) { goto default; } else { goto jumptable[idx]; }