‘Switch’ in C – Jump table formation.

Let me directly use the example to explain. Let the switch case to be
handled is the one given below.

There are 4 cases to be handled in this switch. Now just look into the assembly produced by msp430-gcc.

The compare and jumps are used to handle the switch cases. Now slightly increase the the number of switch cases. It can be seen that when the number of cases become more than certain limit the switch cases are hanled in a different way.These compare and jumpstatements vanishes.For example


Note that L18 label. We can see a table with some values indicated by some other labels ‘.word’. Here a jump table or a look up table is created by the compiler where the address corresponding to each cases is stored. First the stack pointer is decremented by 2 to store the value of the local variable i. And the value of i(here 1) is moved to the stack.The value compared with 15. and if its found higher or same as 15 its moved to end of the program address labeled as L20. Now the value of i in stack is moved to r15. It is multiplied by 2(rla-rotate left arithmetic). This is done to make the offset in the table even (address locations in the table differ by a word which has address to handle each switch cases). Now the offset is added with the base address of the table L18.Let us analyse it using a mspdebugger.

The label L18 is an address location 0xf852. This is the jump table

On peeping into these location it can be seen that each consecutive word is an address location stored in little end form. 0xf852 +(1*2)=0xf854 has the address 0xf876.Here it branches directly to this location


Its clear that 0xf876 is the location with instuctions to handle the case 1.
For intel, this jump table formationcan be observed when the switch cases exceeds 4. msp430 however creates jump table when the number of switch cases exceeds 12 or 13. It may be because of the plenty of registers it have.