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.

Table 1. Data Types on AVR 8-bit Microcontrollers in <stdint.h>
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
Be aware that certain compiler -switches can change this (avr-gcc -mint8 turns the integer data type to an 8-bit integer). The table below shows the effect of different data types and sizes. The output from the avr-size utility shows the code space we used when this application is built with -Os (Optimize for size).
Table 2. Example of Different Data Types and Sizes
Unsigned Int (16bit) Unsigned Char (8bit)
C source code
include <avr/io.h>
unsigned int readADC() {
 return ADCH;
};
int main(void)
{
 unsigned int mAdc = readADC();
}
#include <avr/io.h>
unsigned char readADC() {
return ADCH;
};
int main(void)
{
unsigned char mAdc = readADC();
}
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.

Note: There is a start-up code before running from main(). That’s why a simple C code takes up about 90 bytes.