पाठ 16 / 25
Data Types and Fixed-width Integers
Why uint8_t beats int on a microcontroller.
Sizes that depend on the target
In C and C++ the size of int depends on the platform. On 8-bit AVR boards such as the Uno R3, int is 16 bits (range -32768 to 32767) and double is the same 32-bit type as float; on 32-bit boards like the ESP32, int is 32 bits. Code that silently overflows on one board can work on another. <stdint.h> provides fixed-width types: uint8_t, int16_t, uint32_t and so on, which say exactly what you mean and save precious RAM. Watch for overflow in intermediate expressions (for example 1000 * 100 overflows a 16-bit int) and prefer integer maths over floating point on chips without a hardware FPU.
Below the Arduino API
Embedded C gives you exact sizes, memory placement and direct control of hardware registers.
Overflow on a 16-bit int
Plain embedded C; behaviour noted for AVR (16-bit int).
#include <stdint.h>
uint8_t brightness = 255; /* 0..255, one byte */
int16_t offset = -40; /* signed, two bytes */
uint32_t uptime_ms = 0; /* large counter, four bytes */
void example(void) {
int16_t bad = 1000 * 100; /* overflow: 100000 does not fit in 16 bits */
int32_t good = 1000L * 100; /* L suffix forces 32-bit arithmetic */
uint32_t scaled = (uint32_t)brightness * 1000u / 255u; /* widen before multiplying */
(void)bad; (void)good; (void)scaled;
}Use the smallest correct type
Pick the smallest type that can hold the full range, but widen before multiplying. Saving a byte is pointless if the arithmetic overflows.
त्वरित जाँच: How many bits is an int on an ATmega328P-based Arduino Uno R3?
- 32
- 8
- 16
- 64
Answer
16 — AVR-GCC uses a 16-bit int, unlike most 32-bit platforms.