Traditionally, embedded software was always written in assembly language. This is no longer the case and C and C++ are the dominant languages favored by most embedded developers. However, if code needs to be totally optimal, should assembly language still be used?
The obvious and intuitive answer is yes. A skilled human programmer, with a good knowledge of the target chip’s architecture, capabilities, and assembly language must always be able to do better than a compiler. How can it be otherwise? Modern compilers are good, but not that good.
This conclusion neglects to consider human nature, which changes everything. A good human programmer would aim to write code that’s not only optimal, but also maintainable. A developer wouldn’t want to completely rewrite any code just because some small aspect of the requirements changed. A compiler doesn’t care.
I can illustrate with an example. In C, a switch is a flexible and readable control structure, facilitating multi-way decisions in a very clear way. Broadly speaking, and for the purposes of this example, a switch statement might take one of four forms:
- A very small number of case values (perhaps four or fewer).
- A sequence of consecutive case values.
- A sequence of case values that are almost consecutive, with a few gaps.
- A range of case values that completely non-contiguous.
A compiler would most likely take a different approach to code generation for each case, according to its idea of what is optimal:
(1) would be a series of if-then-else structures.
(2) would be a table of addresses for the code for each case value, and switch control variable would be used to index into the table.
(3) would be very like (2), but with dummy table entries.
(4) would be a look-up table of case values and associated code addresses.
None of these code generation strategies is right, but each is appropriate and optimal for the specific situation. A human programmer would almost definitely use a table structure, as this would be easy to change later.
It’s clear that, for switch statements anyway, the compiler wins over the human assembly language programmer. So, using C, in this case anyway, is better than allowing a human being to get involved.
Colin Walls is a member of the marketing department at Mentor Graphics Embedded Software Division.