C++ programming 2 min read

Types and operators

Every variable has a type that fixes its size and range. On a microcontroller, where RAM is counted in kilobytes, fixed-width types like uint8_t say exactly how many bytes a value uses.

uint8_t is 8 bits and holds 0 to 255. int16_t is 16 bits and holds −32,768 to 32,767. uint32_t is 32 bits and holds 0 to 4,294,967,295. Thick lines mark byte boundaries.
Fixed-width types and the ranges they hold.

Arithmetic operators

C++ has the usual +, -, * and /, plus % for the remainder. Dividing two integers drops the fraction.

operators.cppC++
#include <iostream>int main() {    int a = 17;    int b = 5;    std::cout << a + b << ' ' << a - b << ' ' << a * b << '\n';    std::cout << a / b << ' ' << a % b << '\n';}
Output
22 12 85
3 2

Fixed-width types

The size of int depends on the processor: it is 32 bits on an Arm Cortex-M but only 16 bits on an 8-bit AVR. The header <cstdint> provides types with exact widths, such as uint8_t, int16_t and uint32_t, which is what you want for registers and protocol fields.

overflow.cppC++
#include <cstdint>#include <iostream>int main() {    std::uint8_t level = 250;    level += 10;   // wraps around past 255    std::cout << "level: " << static_cast<int>(level) << '\n';}
Output
level: 4