Fundamental Types

Variable Declarations

c++
type variable = value;
type variable {value}; // C++11

Quick Overview

Signed Integers

c++
long  l1 = -7856974990L;
long long l2 = 89565656974990LL;
// ' digit separator C++14
long l3 = 512'232'697'499;

Unsigned Integers

c++
unsigned u1 = 12347U; 
unsigned long u2 = 123478912345UL;
unsigned long long u3 = 123478912345ULL;
// non-decimal literals
unsigned x = 0x4A; // hexadecimal
unsigned b = 0b10110101; // binary C++14

Floating Point Types

c++
float       f  = 1.88f;
double d1 = 3.5e38;
long double d2 = 3.5e38L; // C++11
// ' digit separator C++14
double d3 = 512'232'697'499.052;

Comparisons

3-Way Comparisons With <=> C++20

c++
determines the relative ordering of 2 objects:
(a <=> b) < 0 if a < b
(a <=> b) > 0 if a > b
(a <=> b) == 0 if a and b are equal/equivalent
3-way comparisons return a comparison category value that can be compared to literal 0.
The returned value comes from one of three possible categories: std::strong_ordering, std::weak_ordering or std::partial_ordering.

4 <=> 6 → std::strong_ordering::less
5 <=> 5 → std::strong_ordering::equal
8 <=> 1 → std::strong_ordering::greater

Memory Sizes of Fundamental Types

Integer Size Guarantees C++11

c++
#include <cstdint>
  • exact size (not available on some platforms)

    int8_t, int16_t, int32_t, int64_t, uint8_t, …

  • guaranteed minimum size

    int_least8_t, uint_least8_t, …

  • fastest with guaranteed minimum size

    int_fast8_t, uint_fast8_t, …

Fixed_Width Floating Point Type Guarantees C++23

c++
#include <stdfloat>

// storage bits: sign + exponent + mantissa
std::float16_t a = 12.3f16; // 1 + 5 + 10 = 16 bits = 2 B
std::float32_t b = 12.3f32; // 1 + 8 + 23 = 32 bits = 4 B
std::float64_t c = 12.3f64; // 1 + 11 + 52 = 64 bits = 8 B
std::float128_t d = 12.3f128; // 1 + 15 + 112 = 128 bits = 16 B
std::bfloat16_t e = 12.3b16; // 1 + 8 + 7 = 16 bits = 2 B

Type Narrowing

  • conversion from type that can represent more values to one that can represent less
  • may result in loss of information
  • in general no compiler warning – happens silently
  • potential source of subtle runtime bugs
c++
double   d = 1.23456;
float f = 2.53f;
unsigned u = 120u;
double e = f; // OK float → double
int i = 2.5; // NARROWING double → int
int j = u; // NARROWING unsigned int → int
int k = f; // NARROWING float → int

Braced Initialization C++11

c++
type variable { value };
  • works for all fundamental types
  • narrowing conversion ⇒ compiler warning
c++
double   d {1.23456};  // OK
float f {2.53f}; // OK
unsigned u {120u}; // OK
double e {f}; // OK float → double
int i {2.5}; // COMPILER WARNING: double → int
int j {u}; // COMPILER WARNING: unsigned int → int
int k {f}; // COMPILER WARNING: float → int

References

https://hackingcpp.com/cpp/lang/fundamental_types.html