C to assembly: if and switch statements

This article covers the code generation for if-else and switch statements. We have already covered C function calls and other C statements in previous articles.

Code generation for "if-else" statement

Code generation for an if-else statement is straight forward. The assembly code exactly mirrors the C code.

Code generation for if-else statement

Code generation for switch statement

The code generated for a switch statement varies a lot from one compiler to another. In fact, a given compiler might generate different code in different scenarios. The choice of the code to be generated depends upon the number and range spread of individual case statements.

Different cases of generation of a switch statement are:

Case values in narrow range

If the case values are placed in a narrow range, the compiler can avoid performing a comparison for every case leg in the switch statement. In such cases, the compiler generates a jump table which contains addresses of the actions to be taken on different legs. The value on which the switch is being performed is manipulated to convert it into an index into the jump table. In this implementation, the time taken in the switch statement is much less than the time taken in an equivalent if-else-if statement cascade. Also, the time taken in the switch statement is independent of the number of case legs in the switch statement.

Switch jump table

Code generation for a switch statement (case values are in a narrow range)

Case values in wide range

If the case legs of the switch statement have a wide deviation in values, the compiler cannot make a jump table to handle the switch statement. In such cases, the jump table would be huge in size and filled very sparingly. Thus the compiler resorts to using a cascade of comparisons to implement the switch. The code generated for the switch statement in such cases will look more like a series of if-else-if statements. Here the time taken to execute the switch statement increases with the number of case legs in the switch.

Generation for switch statement (case values are in a wide range)

Big switch statement with wide distribution

If the switch statement has a very large number of case legs and the values are widely distributed, some compilers use binary search to select the case leg. The different case values are sorted by the compiler at compile time for a binary search.

Explore more