6. TIPS

Next: 6.1 Porting code from Up: SDCC Compiler User Guide Previous: 5.1.7 Interfacing SDCDB with Contents Index

# 6. TIPS

Here are a few guidelines that will help the compiler generate more efficient code, some of the tips are specific to this compiler others are generally good programming practice.

- Use the smallest data type to represent your data-value. If it is known in advance that the value is going to be less than 256 then use an 'unsigned char' instead of a 'short' or 'int'. Please note, that ANSI C requires both signed and unsigned chars to be promoted to 'signed int' before doing any operation. This promotioncan be omitted, if the result is the same. The effect of the promotion rules together with the sign-extension is often surprising:

  > `unsigned char uc = 0xfe;`
  > `if (uc * uc < 0) /* this is true! */`
  > `{`
  > `....`
  > `}`

  `uc * uc` is evaluated as `(int) uc * (int) uc = (int) 0xfe * (int) 0xfe = (int) 0xfc04 = -1024`.
  Another one:

  > `(unsigned char) -12 / (signed char) -3 = ...`

  No, the result is not 4:

  > `(int) (unsigned char) -12 / (int) (signed char) -3 =`
  > `(int) (unsigned char) 0xf4 / (int) (signed char) 0xfd =`
  > `(int) 0x00f4 / (int) 0xfffd =`
  > `(int) 0x00f4 / (int) 0xfffd =`
  > `(int) 244 / (int) -3 =`
  > `(int) -81 = (int) 0xffaf;`

  Don't complain, that gcc gives you a different result. gcc uses 32 bit ints, while SDCC uses 16 bit ints. Therefore the results are different.
  From ''comp.lang.c FAQ'':

  > If well-defined overflow characteristics are important and negative values are not, or if you want to steer clear of sign-extension problems when manipulating bits or bytes, use one of the corresponding unsigned types. (Beware when mixing signed and unsigned values in expressions, though.)
  > Although character types (especially unsigned char) can be used as "tiny" integers, doing so is sometimes more trouble than it's worth, due to unpredictable sign extension and increased code size.

- Use unsigned when it is known in advance that the value is not going to be negative. This helps especially if you are doing division or multiplication, bit-shifting or are using an array index.
- NEVER jump into a LOOP.
- Declare the variables to be local whenever possible, especially loop control variables (induction).
- Have a look at the assembly listing to get a ''feeling'' for the code generation.

Subsections

- 6.1 Porting code from or to other compilers
- 6.2 Tools included in the distribution
- 6.3 Documentation included in the distribution
- 6.4 Related open source tools
- 6.5 Related documentation / recommended reading
- 6.6 Application notes specifically for SDCC
- 6.7 Some Questions

Next: 6.1 Porting code from Up: SDCC Compiler User Guide Previous: 5.1.7 Interfacing SDCDB with Contents Index