Simple Implementation

Simple if-statements can be easily implemented using branch instructions. However, the obvious implementation can become problematic for long nested conditions, and can be unnecessarily slow due to the large number of comparisons. For complex conditions, this cannot be avoided. For switch statements, however, an Address Table can be used.

Address Table

For switch statements, the variable’s value can be used as an index (perhaps after manipulation) to find the address of the instruction to be executed. A lookup table must first be defined for the expected values:

table DEFW case0
      DEFW default
	  DEFW case2
      DEFW default
      DEFW case4

where the values are labels corresponding to each case:

case0   ...
		B end
default ...
		B end
end     ...

This can then be used to execute the instructions corresponding to the value at an address:

LDR R0, number
CMP R0, #0
BLT default ;we don't have an entry with idx < 0, so use the default
CMP R0, #4
BGT default ;we don't have an entry with idx > 4, so use the default

ADR R1, table ; load the address of the first item in the table
LDR PC, [R1, R0, LSL #2] ; multiply R0 by 4 as the word size is 4B