C++ · Module 2 · Lesson 61 min read

Integer Limits & Fixed-Width Types

Every integer type has a range

Type (typical)MinMax
int (32-bit)−2,147,483,6482,147,483,647
unsigned int04,294,967,295
long long (64-bit)≈ −9.22 × 10¹⁸≈ 9.22 × 10¹⁸

std::numeric_limits (<limits>)

c
std::numeric_limits<int>::max()
std::numeric_limits<int>::min()
std::numeric_limits<double>::epsilon()   // smallest step near 1.0

Overflow

  • Signed overflow (INT_MAX + 1) is undefined behaviour ⚠️ — anything can happen
  • Unsigned overflow wraps around (well-defined): 0u - 1 → 4294967295

Prevent overflow

  • Use a bigger type (long long) for large values: populations, money in paisa, file sizes
  • Check before you add: if (a > max - b) { /* would overflow */ }
  • Compute in a wider type: long long product = static_cast<long long>(a) * b;

Fixed-width types (<cstdint>)

When the exact size matters (file formats, networking, embedded):

TypeSize
std::int8_t, std::uint8_t8 bits
std::int16_t, std::uint16_t16 bits
std::int32_t, std::uint32_t32 bits
std::int64_t, std::uint64_t64 bits
std::size_tunsigned, big enough for any object size (used by sizeof, containers)

⚠️ std::int8_t/std::uint8_t usually behave as char with cout — cast to int to print the number.

Floating-point limits

  • double can't represent most decimals exactly: 0.1 + 0.2 != 0.3
  • Compare with a tolerance: std::abs(a - b) < 1e-9
  • Never use double for money that must be exact

Example

C++
#include <cmath>
#include <cstdint>
#include <iostream>
#include <limits>

int main() {
    std::cout << "int range: " << std::numeric_limits<int>::min() << " to "
              << std::numeric_limits<int>::max() << '\n';
    std::cout << "long long max: " << std::numeric_limits<long long>::max() << '\n';

    unsigned int zero = 0;
    std::cout << "unsigned 0 - 1 wraps to " << zero - 1 << '\n';

    int a = 2'000'000'000, b = 2'000'000'000;
    long long safe_sum = static_cast<long long>(a) + b;      // computed in 64 bits
    std::cout << "safe sum: " << safe_sum << '\n';
    bool would_overflow = a > std::numeric_limits<int>::max() - b;
    std::cout << "int a + b would overflow? " << std::boolalpha << would_overflow << '\n';

    std::uint8_t level = 200;
    std::cout << "uint8_t printed as number: " << static_cast<int>(level) << '\n';
    std::cout << "sizeof(std::int64_t) = " << sizeof(std::int64_t) << '\n';

    double x = 0.1 + 0.2;
    std::cout << "0.1 + 0.2 == 0.3 ? " << (x == 0.3) << '\n';
    std::cout << "close enough? " << (std::abs(x - 0.3) < 1e-9) << '\n';
    return 0;
}

/* Output:
int range: -2147483648 to 2147483647
long long max: 9223372036854775807
unsigned 0 - 1 wraps to 4294967295
safe sum: 4000000000
int a + b would overflow? true
uint8_t printed as number: 200
sizeof(std::int64_t) = 8
0.1 + 0.2 == 0.3 ? false
close enough? true
*/