This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Switch / Case Optimization

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

Parents
  • 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.

Reply
  • 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.

Children