Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Numbers & operators

Choose a numeric type

C++

short/int/long/long long have ordered minimum widths, not one universal size. <cstdint> supplies exact-width types when supported. float/double/long double differ in precision; bool is separate.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstdint>
#include <cstddef>

std::int32_t count = 24;
std::uint64_t mask = 0xff;
double ratio = 1.5;
bool ready = true;

Recognize limits and overflow

C++

Unsigned arithmetic is modulo its range; signed integer overflow is undefined behavior. numeric_limits describes the selected type. For floating point, min() is the smallest positive normal value, not the most negative value.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <limits>

const auto largest = std::numeric_limits<int>::max();
const auto lowest = std::numeric_limits<double>::lowest();
unsigned n = std::numeric_limits<unsigned>::max();
n += 1; // 0

Read arithmetic, comparisons and bit operations

C++

Integer division truncates toward zero. == compares values according to the operands’ types. Bit operations are easiest to reason about on unsigned values. << and >> are shifts here; streams overload the same symbols.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const int quotient = 7 / 2; // 3
const unsigned mask = 0b1010;
const bool enabled = (mask & 0b0010u) != 0;

Detect integer overflow: safe integers, math/bits, checked_*, __builtin_add_overflow

C++

Beyond the limits in Recognize limits and overflow, this shows checks that run before signed overflow, and its undefined behavior, can happen. C++ splits the rules: unsigned arithmetic is defined to wrap modulo 2^N, while signed integer overflow is undefined behavior. The optimizer is allowed to assume it never happens, so a check written after the fact (if (a + b < a)) can be deleted. A portable check compares against std::numeric_limits before the operation. GCC and Clang provide __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow, which compute the exact result and report whether it fit. std::in_range (C++20) tells you whether a value fits another integer type. Saturating std::add_sat, sub_sat, mul_sat and saturate_cast are C++26 (<numeric>).

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <cstdint>
#include <limits>
#include <optional>
#include <print>
#include <utility>

// Portable checked add: test against the limits before adding,
// because a signed overflow that has already happened is undefined behavior.
std::optional<int> checked_add(int a, int b) {
    if (b > 0 && a > std::numeric_limits<int>::max() - b) return std::nullopt;
    if (b < 0 && a < std::numeric_limits<int>::min() - b) return std::nullopt;
    return a + b;
}

int main() {
    // Unsigned arithmetic is defined to wrap modulo 2^N.
    std::uint8_t u = 255;
    u = static_cast<std::uint8_t>(u + 1);
    assert(u == 0);

    assert(checked_add(40, 2) == 42);
    assert(!checked_add(std::numeric_limits<int>::max(), 1));

    // GCC/Clang extension: computes the infinitely precise result and reports
    // whether it fits in the destination. Works for +, - and * on any integer types.
    long long product = 0;
    bool overflowed = __builtin_mul_overflow(3'000'000'000LL, 4'000'000'000LL, &product);
    assert(overflowed);
    int sum = 0;
    assert(!__builtin_add_overflow(40, 2, &sum) && sum == 42);

    // std::in_range (C++20): does a value fit in another integer type?
    // It compares correctly across signed/unsigned, unlike a raw cast.
    static_assert(std::in_range<std::uint8_t>(255));
    static_assert(!std::in_range<std::uint8_t>(256));
    static_assert(!std::in_range<unsigned>(-1));

    std::println("wrapped u8: {}, checked: {}, overflowed: {}", u, *checked_add(40, 2), overflowed);
}

In practice: check before the operation with a helper, or use the builtins when you only target GCC and Clang. Build tests with -fsanitize=undefined (or -ftrapv) to catch signed overflow. Use unsigned types only when you really want modular arithmetic.

std::add_sat and the other saturating functions need -std=c++26 (c++2c); they are not available in a C++23 build such as this one.

__builtin_*_overflow are compiler extensions; MSVC has no direct equivalent, so cross-platform code uses the numeric_limits check.

C23 standardizes the same check as ckd_add, ckd_sub and ckd_mul in <stdckdint.h> (bool ckd_add(&result, a, b)). Clang (checked with Apple clang 17) accepts the header in C++ mode; C++26 adopts <stdckdint.h> (P3370R1), and libstdc++ 15+ provides it.

Narrow types are promoted to int before arithmetic: two uint16_t values multiplied can overflow int, which is undefined behavior.

Divide integers and take remainders: / and %, Math.trunc, rem_euclid, divide by zero

C++

Beyond the operator summary in Read arithmetic, comparisons and bit operations, this covers negative remainders, Euclidean modulo and the divisions that are undefined behavior. Since C++11, integer division truncates toward zero and % keeps the sign of the dividend, so -7 / 2 is -3 and -7 % 3 is -1. If either operand is floating point, the usual arithmetic conversions make the whole division floating point. Integer division by zero is undefined behavior, as is INT_MIN / -1 (the result overflows). Floating-point division by zero gives inf or NaN on IEEE 754 platforms (numeric_limits<double>::is_iec559). std::fmod truncates like %, and std::remainder rounds the quotient to nearest.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <cmath>
#include <limits>
#include <optional>
#include <print>

// Euclidean modulo for n > 0: the result is in [0, n).
constexpr int mod(int a, int n) { return ((a % n) + n) % n; }

// Integer division by zero, and INT_MIN / -1, are undefined behavior: check first.
std::optional<int> checked_div(int a, int b) {
    if (b == 0 || (a == std::numeric_limits<int>::min() && b == -1)) return std::nullopt;
    return a / b;
}

int main() {
    // Since C++11, integer division truncates toward zero and % keeps the dividend's sign.
    static_assert(7 / 2 == 3);
    static_assert(-7 / 2 == -3);
    static_assert(-7 % 3 == -1);
    static_assert(mod(-7, 3) == 2 && mod(-1, 24) == 23);

    // One floating operand makes the whole division floating point.
    int a = 7, b = 2;
    assert(static_cast<double>(a) / b == 3.5);
    assert(std::floor(-7.0 / 2) == -4.0);

    assert(!checked_div(1, 0));
    assert(!checked_div(std::numeric_limits<int>::min(), -1));
    assert(checked_div(7, 2) == 3);

    // With IEEE 754 doubles (std::numeric_limits<double>::is_iec559),
    // division by zero gives inf or NaN.
    static_assert(std::numeric_limits<double>::is_iec559);
    double zero = 0.0;
    assert(std::isinf(1.0 / zero) && std::isnan(zero / zero));

    // std::fmod truncates the quotient like %; std::remainder rounds it to nearest.
    assert(std::fmod(-7.0, 3.0) == -1.0 && std::remainder(-7.0, 3.0) == -1.0);
    assert(std::fmod(8.0, 3.0) == 2.0 && std::remainder(8.0, 3.0) == -1.0);  // 8/3 rounds to 3
    std::println("{} {} {} {} {} {}", -7 / 2, -7 % 3, mod(-7, 3), std::fmod(8.0, 3.0),
                 std::remainder(8.0, 3.0), 1.0 / zero);
}

In practice: check the divisor (and the INT_MIN / -1 case) before dividing untrusted integers, use ((a % n) + n) % n for a non-negative modulo, and static_cast one operand to double when you want a fractional result.

A divide-by-zero on integers often crashes with SIGFPE on x86, but because it is undefined behavior the compiler may also remove code around it; do not rely on the crash.

Build tests with -fsanitize=undefined to report integer division by zero and INT_MIN / -1.

Convert between numeric types: Math.trunc, T(x), as + TryFrom, static_cast

C++

Beyond the type list in Choose a numeric type, this covers which conversions are implicit, which are undefined behavior, and how to check them. C++ converts arithmetic types implicitly, including narrowing ones such as double to int, often with only a warning. Integer to unsigned conversion is modulo 2^N, and since C++20 integer to signed is modulo 2^N as well. Float to integer truncates toward zero, and is undefined behavior if the truncated value does not fit. Brace initialization (int i{2.5}) rejects narrowing at compile time, and std::in_range (C++20) checks whether an integer fits another integer type.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <cmath>
#include <cstdint>
#include <limits>
#include <optional>
#include <print>
#include <utility>

// Checked narrowing: std::in_range (C++20) compares signed and unsigned correctly.
template <class To, class From>
std::optional<To> narrow(From value) {
    if (!std::in_range<To>(value)) return std::nullopt;
    return static_cast<To>(value);
}

// Float -> int is undefined behavior when the truncated value does not fit, so check first.
std::optional<std::int32_t> to_int32(double d) {
    if (!(d > -2147483649.0 && d < 2147483648.0)) return std::nullopt;  // also rejects NaN
    return static_cast<std::int32_t>(d);                                // truncates toward zero
}

int main() {
    // Integer -> unsigned keeps the value modulo 2^N (defined).
    assert(static_cast<std::uint8_t>(300) == 44);
    assert(static_cast<std::uint32_t>(-1) == 4294967295u);
    // Integer -> signed that does not fit is also modulo 2^N since C++20.
    assert(static_cast<std::int8_t>(200) == -56);

    // Brace initialization rejects narrowing at compile time:
    // std::uint8_t b{300};  // error: constant expression evaluates to 300
    // int i{2.5};           // error: narrowing conversion from double

    assert(narrow<std::uint8_t>(200) == 200);
    assert(!narrow<std::uint8_t>(300));
    assert(!narrow<unsigned>(-1));

    assert(to_int32(-2.7) == -2);
    assert(!to_int32(1e10));
    assert(!to_int32(std::nan("")));
    assert(std::lround(-2.5) == -3);  // rounds half away from zero

    // Integer -> double loses precision above 2^53.
    std::int64_t n = (std::int64_t{1} << 53) + 1;
    assert(static_cast<std::int64_t>(static_cast<double>(n)) != n);

    std::println("{} {} {}", static_cast<int>(static_cast<std::uint8_t>(300)), *to_int32(-2.7),
                 narrow<std::uint8_t>(300).has_value());
}

In practice: write conversions with static_cast so they are visible, initialize with braces to catch narrowing, and wrap narrowing of runtime values in a checked helper using std::in_range. Range-check doubles before casting them to integers; use std::lround or std::llround when you want rounding instead of truncation.

-Wconversion (not part of -Wall or -Wextra) warns about implicit narrowing; add it to catch lossy assignments.

C++26 adds std::saturate_cast in <numeric> for clamping integer conversions; it is not available in a C++23 build.

Compare floats and keep money in integer cents: EPSILON, math.IsNaN, total_cmp, std::signbit

C++

Beyond the type list in Choose a numeric type and the decimal libraries in Big numbers & decimals, this covers comparing floats, NaN in sorted containers, negative zero and keeping money in integer cents. float and double are IEEE 754 binary formats on mainstream platforms (std::numeric_limits<double>::is_iec559), so 0.1 + 0.2 != 0.3. NaN compares unequal to everything; std::isnan detects it, and any ordering-based algorithm (std::sort, std::set) behaves badly if NaN values are present, because < is no longer a strict weak ordering. -0.0 == 0.0, while std::signbit shows the sign. numeric_limits<double>::epsilon() is the gap between 1.0 and the next value.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <limits>
#include <print>

bool nearly_equal(double a, double b, double rel = 1e-9, double abs = 1e-12) {
    return std::fabs(a - b) <= std::max(rel * std::max(std::fabs(a), std::fabs(b)), abs);
}

int main() {
    double x = 0.1 + 0.2;
    assert(x != 0.3);
    assert(nearly_equal(x, 0.3));
    std::println("{} epsilon {}", x, std::numeric_limits<double>::epsilon());

    // NaN compares unequal to everything, itself included.
    double nan = std::numeric_limits<double>::quiet_NaN();
    assert(nan != nan && std::isnan(nan));

    // -0.0 == 0.0, but signbit and division see the sign.
    double neg_zero = -0.0;
    assert(neg_zero == 0.0 && std::signbit(neg_zero));
    assert(std::isinf(1.0 / neg_zero) && 1.0 / neg_zero < 0);

    // Money: integer cents, round once. std::llround rounds half away from zero.
    std::int64_t total = 1999 * 3;
    std::int64_t tax = std::llround(total * 825 / 10'000.0);
    assert(total + tax == 6492);
    std::println("total: {}.{:02}", (total + tax) / 100, (total + tax) % 100);
}

In practice: compare with a relative plus absolute tolerance, filter or reject NaN before sorting, and keep money in std::int64_t cents with std::llround at the boundary. C++ has no standard decimal type.

For decimal arithmetic, Boost.Multiprecision (Boost 1.92.0) offers cpp_dec_float; there is no std::decimal (a decimal TR was never adopted into the standard).

-ffast-math lets the compiler assume no NaN or infinity, which can make std::isnan always return false; avoid it in code that checks for NaN.

std::strong_order for floating point (C++20) gives the IEEE total order, like Rust's total_cmp.

Parse and format numbers: Number + Intl.NumberFormat, strconv + fmt, parse + format!, from_chars + std::format

C++

Beyond the basic calls in Text ↔ number conversion and Printing & formatting, this covers a strict from_chars parser, and output width, precision, rounding and separators. std::from_chars (C++17, <charconv>) is the fast, locale-independent parser: it returns a pointer to the first unparsed character and a std::errc (invalid_argument or result_out_of_range), never throws and never allocates. It does not skip whitespace or accept a leading +, and it stops at the first non-digit, so compare the returned pointer with the end to reject "12px". std::stoi and friends are older: they skip whitespace, accept trailing junk and throw std::invalid_argument or std::out_of_range. std::format (C++20) and std::print (C++23) format with {:.2f}, {:5}, {:<5}, {:05}, {:#x}.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <charconv>
#include <cmath>
#include <format>
#include <optional>
#include <print>
#include <string>
#include <string_view>
#include <system_error>

// std::from_chars (C++17): no locale, no exceptions, no allocation.
// Require that every character was consumed, or "12px" would parse as 12.
template <class T>
std::optional<T> parse_number(std::string_view text) {
    T value{};
    auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), value);
    if (ec != std::errc{} || end != text.data() + text.size()) return std::nullopt;
    return value;
}

std::string group(long long n) {
    // Negate in unsigned arithmetic so LLONG_MIN does not overflow.
    unsigned long long magnitude = n < 0 ? 0ULL - static_cast<unsigned long long>(n) : n;
    std::string digits = std::to_string(magnitude), out;
    for (std::size_t i = 0; i < digits.size(); ++i) {
        if (i > 0 && (digits.size() - i) % 3 == 0) out += ',';
        out += digits[i];
    }
    return n < 0 ? "-" + out : out;
}

int main() {
    assert(parse_number<int>("42") == 42);
    assert(!parse_number<int>("12px"));
    assert(!parse_number<int>(" 42"));   // no leading whitespace
    assert(!parse_number<int>("+42"));   // no leading +
    assert(!parse_number<unsigned char>("300"));  // errc::result_out_of_range
    assert(parse_number<double>("3.14") == 3.14);

    // Out of range is reported separately from bad input.
    int v = 0;
    std::string_view big = "99999999999";
    auto result = std::from_chars(big.data(), big.data() + big.size(), v);
    assert(result.ec == std::errc::result_out_of_range);

    // std::stoi throws instead (std::invalid_argument / std::out_of_range) and accepts "12px".
    assert(std::stoi("12px") == 12);

    // std::format (C++20): precision, width, alignment, zero padding.
    assert(std::format("{:.2f}", 3.14159) == "3.14");
    assert(std::format("[{:5}] [{:<5}] [{:05}] [{:>8.3f}]", 42, 42, 42, 3.14159) ==
           "[   42] [42   ] [00042] [   3.142]");
    assert(std::format("{:#x} {:08b}", 255, 5) == "0xff 00000101");
    assert(group(-1234567) == "-1,234,567");

    // Rounding to 2 decimals: std::format rounds an exact tie (0.125 is exact in binary)
    // to even, while std::round rounds half away from zero.
    assert(std::format("{:.2f} {:.0f}", 0.125, 2.5) == "0.12 2");
    assert(std::round(0.125 * 100) / 100 == 0.13);

    std::println("{} {:.2f} {}", *parse_number<int>("42"), 3.14159, group(1234567));
}

In practice: parse with a small from_chars helper that checks both ec and the end pointer, and format with std::format. Use {:L} with a std::locale only when you need locale-specific separators, because the locale names available differ by platform. When rounding to 2 decimals, std::format rounds an exact tie such as 0.125 to even (0.12) while std::round(x * 100) / 100 rounds it away from zero (0.13), so choose one rule for money and apply it to integer cents.

Floating-point std::from_chars reached the standard libraries late (GCC 11, MSVC 2019, libc++ only in LLVM 20); older toolchains accept it only for integers.

std::format("{:L}", n) uses the global locale, which is the "C" locale unless the program sets one, so it prints no separators by default.

Use integers wider than 64 bits: BigInt, math/big, u128, unsigned __int128

C++

Beyond the overview in Big numbers & decimals, this shows the __int128 extension: what works with it, how to print it and where it stops. Standard C++ has no big integer type, and the widest standard integer is usually 64 bits (long long / std::int64_t). GCC and Clang provide unsigned __int128 and __int128 as an extension on 64-bit targets: arithmetic and __builtin_mul_overflow work with them, and std::format and std::print format them (in both libc++ and libstdc++), but iostreams and std::to_string do not, and with libstdc++, type traits such as std::is_integral report __int128 only in GNU modes (-std=gnu++23, not -std=c++23), while std::numeric_limits is specialized in both. For unbounded integers use Boost.Multiprecision (cpp_int, header-only) or GMP.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <cstdint>
#include <format>
#include <limits>
#include <optional>
#include <print>

// The standard library has no big integer type. GCC and Clang provide
// unsigned __int128 as an extension; beyond that, use Boost.Multiprecision or GMP.
using u128 = unsigned __int128;

std::optional<u128> factorial(unsigned n) {
    u128 result = 1;
    for (unsigned i = 2; i <= n; ++i) {
        if (__builtin_mul_overflow(result, i, &result)) return std::nullopt;
    }
    return result;
}

int main() {
    // uint64_t holds every 19-digit number: 20! fits, 21! does not.
    static_assert(std::numeric_limits<std::uint64_t>::digits10 == 19);

    auto f30 = factorial(30);
    // std::format and std::print handle __int128; iostreams and std::to_string do not.
    assert(f30 && std::format("{}", *f30) == "265252859812191058636308480000000");
    assert(factorial(34) && !factorial(35));

    u128 wide = static_cast<u128>(UINT64_MAX) * UINT64_MAX;
    std::println("30! = {}\nu64 max squared = {}", *f30, wide);
}

In practice: use __int128 only for wide intermediates in GCC/Clang code, print it with std::print or std::format, and switch to Boost.Multiprecision when numbers are unbounded or MSVC must build the code.

Boost.Multiprecision (Boost 1.92.0) provides cpp_int (arbitrary precision) and fixed sizes such as uint256_t, with no separate build step.

MSVC has no __int128; C23 _BitInt(N) is available in Clang's C++ mode as an extension, not in standard C++.