C++
    Overview
    Modern C++
    Language Concepts
    Operators
    Numerics
    Smart Pointers
    Containers
    Functions
    Memory Management
    Caveats
    Type Casting
    Trouble Shooting

C++ - Numerics

Updated: 2022-02-12

Variable-width Integers

short, int, long

C leaves the size of an integer open: the compiler implementors could pick a size for int that performs best on the target computer architecture.

C++ only guarantees that integer variables will have a minimum size -- but they could be larger, depending on the target system.

x86_64 int is 32 bits, a long is 64 bits, and a pointer is 64 bits.

Fixed-width Integers

You should prefer the fixed-width integral types. (https://google.github.io/styleguide/cppguide.html#Integer_Types) Do not use built-in integer type other than int (use int for integers we know are not going to be too big).

Fixed-width Integers were introduced in C99 (in stdint.h header) and C++11 (in cstdint header)

Types with a prefix u are unsigned.

type bytes range
std::int8_t 1 byte -128 to 127
std::uint8_t 1 byte 0 to 255
std::int16_t 2 byte -32,768 to 32,767
std::uint16_t 2 byte 0 to 65,535
std::int32_t 4 byte -2,147,483,648 to 2,147,483,647
std::uint32_t 4 byte 0 to 4,294,967,295
std::int64_t 8 byte -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
std::uint64_t 8 byte 0 to 18,446,744,073,709,551,615

std::int8_t and std::uint8_t may be treated as signed char and unsigned char respectively.

It is safe for code to assume that <cstdint> defines the type aliases int64_t in the global namespaces as well as in namespace std.

Fast and Least Types

C++ also defines two alternative sets of integers.

The fast type (std::int_fast#_t) provides the fastest signed integer type with a width of at least # bits (where # = 8, 16, 32, or 64). For example, std::int_fast32_t will give you the fastest signed integer type that’s at least 32 bits.

The least type (std::int_least#_t) provides the smallest signed integer type with a width of at least # bits (where # = 8, 16, 32, or 64). For example, std::int_least32_t will give you the smallest signed integer type that’s at least 32 bits.