C++ - Numbers & Numeric Limits

Overview

Estimated time: 35–45 minutes

Work with numbers in C++: integer and floating-point types, conversions, and numeric limits. Avoid truncation and overflow surprises.

Learning Objectives

  • Choose appropriate numeric types and convert safely.
  • Use std::numeric_limits to query ranges and properties.

Prerequisites

Types and conversions

int i = 3.9;      // truncates to 3
double d = 42;    // implicit integral to floating
auto big = std::numeric_limits::max();

numeric_limits

#include <limits>
#include <iostream>
int main(){
  std::cout << std::numeric_limits<int>::min() << ".." 
            << std::numeric_limits<int>::max() << "\n";
}

Common Pitfalls

  • Narrowing conversions with list-initialization are disallowed; prefer braces to catch mistakes: int x{3.9}; // error
  • Unsigned underflow/overflow wraps modulo 2^N.