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.
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