247/317
8 - C Language and the C Compiler
However, this does not mean that you should adopt a loose programming style, as it is often
the case when programming for computers. There, a clear style, using techniques that can be
quickly written, is recommended, but this may be at the expense of memory and/or the proc-
essor resource.
When programming in C for microcontrollers, you must keep in mind that both memories (pro-
gram and data) are scarce, and that the processor speed is not elastic. This means that you
must carefully design your program to avoid wasting either the memory or the processor cy-
cles. Of course, the very purpose of a high-level language is to hide the machine instructions
from you; so you cannot know exactly how your code is translated.
It is still possible to set up a few rules that will help your programs avoid wasting resources.
8.8.4.1 Define a function when a group of statements is repeated several times
The C language is powerful and may generate a lot of code for a single line. For example, the
following statement:
for ( p1 = string1, p2 = string2
; ( *p2 = *p1 ) ; p1++, p2++ ) ;
copies one string to another by copying each byte from the first location in memory to the
second one, incrementing both pointers, looping back and stopping when the zero character
is encountered.
The code generated occupies 95 bytes of memory. This illustrates that it may be beneficial in
terms of memory usage to define a function for a piece of code that is repeated several times,
even sometimes it is only a single line.
8.8.4.2 Use shifts instead of multiplication and division
Division, and to a lesser degree multiplication, are very time-consuming operations. When the
divisor is a power of two, it is much more efficient to use shifts instead. Example:
A = B / 16 ;
is better replaced by
A = B >> 4 ;
The compiler handles shifts in a very optimized way; for example, if a word is shifted right by
8 places, the compiler merely takes the high-order byte of the source and puts it in the low-
order byte of the destination, and clears the high-order byte of the destination.