Sub topic 4
Choosing the smallest data type that fits
On an Uno-class board, every global variable permanently takes some of the 2048 bytes of SRAM. This chapter shows how to pick a type for each value so it is large enough to be correct and no larger than needed. It assumes you can write and upload a sketch, know C/C++ basics (variables, arrays, functions), and can read output in the Serial Monitor. The sizes below are for AVR boards such as the Uno and Nano. Other boards differ, as the last section explains.
Why type size matters for SRAM
A variable's type fixes how many bytes it occupies. The cost grows with arrays, because the size is multiplied by the element count. An array of 200 int values uses 400 bytes, which is about 20% of an Uno's SRAM. The same data in uint8_t uses 200 bytes.
Types matter most for global and static variables and arrays. They stay in SRAM for the whole run, and the build report counts them. Local scalar variables are often kept in CPU registers or on the stack briefly, so shrinking them rarely helps memory. It can still help speed, as covered later.
Check the sizes on your own board
Do not rely on memory for type sizes. Ask the compiler with sizeof:
void setup() {
Serial.begin(9600);
Serial.print(F("char: ")); Serial.println(sizeof(char));
Serial.print(F("bool: ")); Serial.println(sizeof(bool));
Serial.print(F("int: ")); Serial.println(sizeof(int));
Serial.print(F("long: ")); Serial.println(sizeof(long));
Serial.print(F("long long: ")); Serial.println(sizeof(long long));
Serial.print(F("float: ")); Serial.println(sizeof(float));
Serial.print(F("double: ")); Serial.println(sizeof(double));
Serial.print(F("pointer: ")); Serial.println(sizeof(void *));
}
void loop() {
}On an Uno this prints 1, 1, 2, 4, 8, 4, 4 and 2. Two results surprise people. int is only 16 bits, and double is the same size as float, so using double does not buy extra precision on AVR.
The types worth knowing
The fixed-width types from <stdint.h> state their size in the name. They are available in Arduino sketches without an extra include. Prefer them for arrays and stored data, because int and long change size between boards.
| Type | Bytes | Range | Typical use |
|---|---|---|---|
| `bool` | 1 | `false` or `true` | One on/off state |
| `uint8_t` (`byte`) | 1 | 0 to 255 | Pin numbers, small counters, raw bytes |
| `int8_t` | 1 | -128 to 127 | Small signed offsets |
| `uint16_t` | 2 | 0 to 65535 | `analogRead()` results, millisecond delays under 65 s |
| `int16_t` | 2 | -32768 to 32767 | Scaled sensor values, signed deltas |
| `uint32_t` | 4 | 0 to 4,294,967,295 | `millis()` and `micros()` timestamps |
| `int32_t` | 4 | about ±2.1 billion | Intermediate math that would overflow 16 bits |
| `float` | 4 | about 7 significant digits | Values that really need fractions |
analogRead() returns a value from 0 to 1023 on a 10-bit converter. That needs 10 bits, so uint16_t is the smallest standard type that holds it. It cannot fit in uint8_t.
A simple decision process
Work out the range of the value first. Then choose the smallest type whose range covers it with a margin for the worst case.
Replace float with scaled integers
A float takes 4 bytes. It also pulls in a software floating-point library, because AVR chips have no floating-point hardware. If your value has a fixed number of decimal places, store it as an integer in smaller units. For example, store temperature in tenths of a degree.
const uint8_t SAMPLE_COUNT = 24;
int16_t levelTenths[SAMPLE_COUNT];
void setup() {
Serial.begin(9600);
for (uint8_t i = 0; i < SAMPLE_COUNT; i++) {
int raw = analogRead(A0);
// Map 0..1023 to 0..1000 tenths of a percent, using 32-bit math.
levelTenths[i] = (int16_t)((raw * 1000L) / 1023);
}
int16_t t = levelTenths[0];
Serial.print(t / 10);
Serial.print('.');
Serial.println(t % 10);
}
void loop() {
}The array uses 48 bytes. The same array of float would use 96. The 1000L literal matters. Without it, raw * 1000 is computed in 16-bit int and overflows for any raw above 32. The next section explains why.
Integer promotion and overflow
Small types do not stay small during arithmetic. C++ promotes uint8_t and uint16_t operands to int before it calculates, and int is 16 bits here. An expression that mixes only small constants and variables can therefore overflow even when the result seems to fit in the destination.
void setup() {
Serial.begin(9600);
uint8_t counter = 250;
for (uint8_t n = 0; n < 10; n++) {
Serial.println(counter);
counter++;
}
unsigned long wrong = 60 * 1000;
unsigned long right = 60UL * 1000UL;
Serial.println(wrong);
Serial.println(right);
}
void loop() {
}The first loop prints 250 up to 255, then wraps to 0, 1, 2 and 3. Unsigned wraparound is well defined in C++, and it is sometimes useful. The second part is a bug. 60 * 1000 is computed as int, and 60000 does not fit in a 16-bit signed int. The compiler may warn about it, and the stored value is wrong. Signed overflow is undefined behavior in C++, so do not depend on any particular result. The suffix UL makes the literal unsigned long and the math is done in 32 bits.
Timers: keep `millis()` as 32 bits
millis() returns unsigned long, which is 32 bits. Storing a timestamp in a uint16_t saves 2 bytes, but the value wraps every 65.5 seconds. Your timing logic will then break unless you account for the wrap. A 32-bit counter wraps after about 49.7 days. Use uint32_t for timestamps and compare with subtraction:
uint32_t lastBlink = 0;
const uint16_t BLINK_INTERVAL_MS = 500;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
uint32_t now = millis();
if (now - lastBlink >= BLINK_INTERVAL_MS) {
lastBlink = now;
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
}The subtraction now - lastBlink gives the correct elapsed time even across the wraparound, as long as both values are unsigned 32-bit. The interval itself is small, so it can use the smaller uint16_t. This sketch applies the rule: pick each type for its own range, not one type for everything.
Pack flags into one byte
Each bool takes a full byte. Eight separate bool variables cost 8 bytes. One uint8_t can hold eight flags as individual bits:
const uint8_t FLAG_LED_ON = 1 << 0;
const uint8_t FLAG_ALARM = 1 << 1;
const uint8_t FLAG_LOGGING = 1 << 2;
uint8_t flags = 0;
void setup() {
Serial.begin(9600);
flags |= FLAG_LED_ON;
flags |= FLAG_ALARM;
flags &= ~FLAG_LED_ON;
if (flags & FLAG_ALARM) {
Serial.println(F("Alarm is set"));
}
Serial.println(flags, BIN);
}
void loop() {
}|= sets a bit, &= ~ clears it, and & tests it. The program prints Alarm is set and then 10, which is binary for the value 2. Bit packing saves a few bytes at the cost of readability, so use it when you have many flags or flags stored in arrays. For two or three flags, plain bool variables are clearer.
Constants should not take SRAM
A pin number or a fixed limit does not need a writable variable. Declare it const (or constexpr) with a small type:
const uint8_t LED_PIN = 13;
const uint16_t SAMPLE_INTERVAL_MS = 250;In ordinary use the compiler substitutes the value directly into the machine code and allocates no SRAM for it. A non-const int ledPin = 13; is a real variable in SRAM and also costs extra instructions. Large constant arrays are different. The compiler cannot treat them as immediate values, so they stay in SRAM unless you place them in flash with PROGMEM, covered in a later chapter.
Smaller is not always better
- Speed. The AVR core is 8-bit. Math on
uint8_tis fastest, 16-bit takes a few instructions, and 32-bit math takes noticeably more. Long arithmetic andfloatare the slowest. - Code size. Mixing sizes adds conversion instructions. A sketch that uses
floatanywhere also links in the floating-point routines, which add to flash use. - Safety margin. If the value could ever exceed the type, pick the next size up. A silent wraparound is harder to diagnose than 100 bytes of lost SRAM.
- Portability. Fixed-width types behave the same on every board. On an ARM-based board
intis 32 bits, so code that relied on 16-bit wraparound ofintbehaves differently. - Structs on other cores. AVR has no alignment padding. On 32-bit cores, a struct can contain padding bytes between members. Order members from largest to smallest to reduce it, and check with
sizeof.
Memory sizes on other boards
The advice here matters most on the 2 KB Uno and Nano class. Boards with more SRAM leave more slack, but the same habits keep code portable and predictable. If you are unsure, print sizeof for your structs and arrays on the actual board.
Exercise
A sketch stores 300 readings from analogRead() in an array declared as long readings[300];. How many bytes does it use on an Uno, and what is a better declaration and its new size?
Show answer
A long is 4 bytes on AVR, so the array uses 1200 bytes, which is more than half of the Uno's 2048 bytes of SRAM. analogRead() returns 0 to 1023, which fits in uint16_t. The declaration uint16_t readings[300]; uses 600 bytes, saving 600 bytes.
Exercise
Why does unsigned long ms = 40 * 1000; give a wrong result on an Uno, and how do you fix it?
Show answer
The literals 40 and 1000 are int, which is 16 bits on AVR, so the multiplication is done in int. The result, 40000, exceeds 32767 and overflows before it is assigned to the unsigned long. Writing 40UL * 1000UL makes the math 32-bit and gives 40000.
Exercise
You need to store eight on/off settings. Name two ways to hold them and compare their SRAM use.
Show answer
You can declare eight bool variables, which use 8 bytes because each bool takes one byte. Or you can use one uint8_t with each setting as a bit, which uses 1 byte. The packed version saves 7 bytes but needs bit operations such as |=, &= ~ and &.