9.1.1 Tip #1 Data Types and Sizes
Use the smallest applicable data type possible. Evaluate your code and in particular the data types. Reading an 8-bit (byte) value from a register only requires a single byte variable and not a two byte variable, thus saving code-space and data-space.
The size of data types on the AVR 8-bit microcontrollers can be found in the <stdint.h> header file and is summarized in the table below.
Data type | Size | |
---|---|---|
signed char / unsigned char | int8_t / uint8_t | 8-bit |
signed int / unsigned int | int16_t / uint16_t | 16-bit |
signed long / unsigned long | int32_t / uint32_t | 32-bit |
signed long long / unsigned long long | int64_t / uint64_t | 64-bit |
Unsigned Int (16bit) | Unsigned Char (8bit) | |
---|---|---|
C source code |
|
|
AVR Memory Usage | Program: 92 bytes (1.1% Full) | Program: 90 bytes (1.1% Full) |
Compiler optimization level | -Os (Optimize for size) | -Os (Optimize for size) |
In the left example, we use the int (2-byte) data type as return value from the readADC() function and in the temporary variable used to store the return value from the readADC() function.
In the right example we are using char(1-byte) instead. The Readout from the ADCH register is only 8 bits, and this means that a char is sufficient. 2 bytes are saved due to the return value of the function readADC() and the temporary variable in main being changed from int (2-byte) to char (1-byte).
The difference in size will increase if the variable is manipulated more than what is done in this example. In general both arithmetic and logical manipulation of a 16-bit variables takes more cycles and space than an 8-bit variable.