Programming Search⌘K

Conceptcore

Integer overflow behaviour

Also called overflow semantics, overflow behavior, wrapping arithmetic, wraparound, checked arithmetic, saturating arithmetic, saturation arithmetic, trapping arithmetic, signed overflow.

When an integer result does not fit in its type, a language wraps it, traps, saturates it at the limit, or leaves the behavior undefined. Most languages have a default rule and ways to choose another.

Applies to
core-languages

Idea

An integer type with a fixed width holds a fixed range of values. A 32-bit signed integer holds -2147483648 to 2147483647. The sum 2147483647 + 1 is outside that range, so the hardware cannot give the exact result in 32 bits. This is integer overflow. Each language must have a rule for it, and the rules are not the same. Wikipedia lists the choices in a table: for signed integers, Ada raises Constraint_Error, C and C++ have "undefined behavior", Java wraps "modulo power of two", and Swift "Causes error unless using special overflow operators."1

There are four main rules and one way to avoid the problem:

  • Wrap. Keep the low N bits of the exact result. The result is correct modulo 2ᴺ, so 2147483647 + 1 gives -2147483648.
  • Trap. Stop the operation with an error, an exception or a panic.
  • Saturate. Give the largest or the smallest value of the type, whichever is nearer to the exact result.
  • Undefined. The language makes no promise, and the compiler may assume that overflow never happens.
  • Grow. The integer type has no fixed width, so the exact result always fits.
LO, HI = -128, 127  # the range of an 8-bit signed integer


def wrap(x):
    return (x - LO) % 256 + LO


def saturate(x):
    return max(LO, min(HI, x))


def trap(x):
    if not LO <= x <= HI:
        raise OverflowError(f"{x} does not fit in 8 bits")
    return x


for a, b in ((100, 27), (100, 28), (-100, -29), (127, 127)):
    exact = a + b
    try:
        trapped = trap(exact)
    except OverflowError:
        trapped = "error"
    print(f"{a} + {b}: exact {exact}, wrap {wrap(exact)}, "
          f"saturate {saturate(exact)}, trap {trapped}")
Output
100 + 27: exact 127, wrap 127, saturate 127, trap 127
100 + 28: exact 128, wrap -128, saturate 127, trap error
-100 + -29: exact -129, wrap 127, saturate -128, trap error
127 + 127: exact 254, wrap -2, saturate 127, trap error

How it works

Wrap. A binary adder that gives N bits gives the wrapped result for free. For unsigned values, the Go specification says that the operations "discard high bits upon overflow"2. For signed values, Go says that +, -, *, / and << "may legally overflow", that "Overflow does not cause a run-time panic", and that "A compiler may not optimize code under the assumption that overflow does not occur."2 Java wraps too: "The integer operators do not indicate overflow or underflow in any way."3 C# wraps in an unchecked context, where "the result is truncated by discarding any high-order bits that don't fit in the destination type."4

Undefined. C and C++ wrap unsigned values. For C, "adding one to UINT_MAX gives 0"5. Signed overflow is different. In C, "When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined: it may wrap around according to the rules of the representation (typically 2's complement), it may trap on some platforms or due to compiler options (e.g. -ftrapv in GCC and Clang), or may be completely optimized out by the compiler."5 The rule lets the compiler simplify code. For example, it can assume that x + 1 > x is always true for a signed x. Compiler options change the rule. In GCC, -ftrapv "generates traps for signed overflow on addition, subtraction, multiplication operations"6, and -fwrapv "instructs the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation."6

Trap. Rust treats overflow as a bug: "If a program contains arithmetic overflow, the programmer has made an error."7 Its reference says: "Integer operators will panic when they overflow when compiled in debug mode."8 Other builds may panic or wrap7. Cargo turns the checks on and off with the overflow-checks setting, which is true in the dev profile and false in the release profile9. In C#, a checked context makes overflow throw: "an OverflowException is thrown."4 The compiler option CheckForOverflowUnderflow makes checked the default context, and "The default value for this option is false"10. Java has no checked context, but Math.addExact "Returns the sum of its arguments, throwing an exception if the result overflows" an int11.

Saturate. "Saturation arithmetic is a version of arithmetic in which all operations, such as addition and multiplication, are limited to a fixed range between a minimum and maximum value."12 It is common in signal processing: "adjusting the volume level of a sound signal can result in overflow, and saturation causes significantly less distortion to the sound than wrap-around."12 Rust's saturating_add computes the sum "saturating at the numeric bounds instead of overflowing"13. C++26 adds std::saturating_add in <numeric>14.

Grow. In Python, "Integers have unlimited precision."15 JavaScript numbers are floats, so a large sum is rounded, not wrapped. MDN shows that Number.MAX_SAFE_INTEGER + 1 and Number.MAX_SAFE_INTEGER + 2 are equal16. The JavaScript BigInt type grows, and BigInt.asIntN "truncates a BigInt value to the given number of least significant bits and returns that value as a signed integer"17, which is a wrap on request.

Databases. SQL databases usually reject the value. PostgreSQL says: "Attempts to store values outside of the allowed range will result in an error."18

Operations that choose the rule. Many languages let the program choose the rule for one operation:

Rule C C++ C# Java Rust
wrap unsigned types unsigned types unchecked the operators wrapping_add
trap or report ckd_add (C23) compiler builtins checked Math.addExact checked_add, overflowing_add
saturate by hand std::saturating_add (C++26) by hand by hand saturating_add

C23 ckd_add stores the wrapped result and returns true when it is not "the mathematical result of the operation"19. GCC and Clang have __builtin_add_overflow, and "these built-in functions have fully defined behavior for all argument values"20. Rust's overflowing_add returns "a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur"13, and checked_add returns None on overflow13.

In languages

LanguageVerdictNote
PythonIdiom
C++Standard library
JavaStandard library
CStandard library
C#Native
JavaScriptIdiom
TypeScriptIdiomTypeScript has the number and bigint types of JavaScript, so a sum is rounded, not wrapped, and a program checks the range by hand, as in the JavaScript example. No example file exists.
GoIdiom
RustNative
KotlinIdiomKotlin integers wrap on overflow, as in Java. On the JVM a program can call Math.addExact to trap. No example file exists because kotlinc is not installed.
SQLNativeSQL integer types have fixed ranges, and a value out of range is an error. PostgreSQL says that attempts to store such a value result in an error.
BashIdiomBash arithmetic uses fixed-width integers with no check for overflow, so a script tests the range by hand. No example file exists.
PowerShellIdiomPowerShell widens the type of a result that is too large, so [int]::MaxValue + 1 is not wrapped. A script that needs a fixed width converts and checks by hand. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no arithmetic.
CSSDoes not applyCSS has calc(), but its numbers are not integer types with a fixed width.
Regular expressionsDoes not applyA pattern matches digits as text but does no arithmetic.
Language Verdict Default rule and other choices
Python idiom int grows; wrap by hand with a mask
JavaScript idiom Number rounds; BigInt grows; BigInt.asIntN wraps; | 0 wraps to 32 bits
TypeScript idiom as JavaScript
Java stdlib wraps; Math.addExact throws
Kotlin idiom wraps as in Java; Math.addExact on the JVM
C# native wraps in unchecked; throws in checked
Go idiom wraps; checks by hand
Rust native panics in debug builds; checked_, wrapping_, saturating_ and overflowing_ methods
C stdlib unsigned wraps; signed is undefined; ckd_add in C23
C++ stdlib unsigned wraps; signed is undefined; std::saturating_add in C++26
Bash idiom fixed-width arithmetic with no overflow check
PowerShell idiom widens the result to a larger type
SQL native overflow is an error
Regex n/a no arithmetic
HTML n/a no arithmetic
CSS n/a no integer types with a width

The verdict says how directly a language lets a program choose the rule. C# and Rust have the choices in the language. Java, C and C++ have them in the standard library. Python, JavaScript and Go need code by hand for some rules. PowerShell avoids overflow in a different way: "If the result of an operation is too large for the type, the type of the result is widened to accommodate the result"21.

PythonGitHub
import ctypes

INT32_MIN, INT32_MAX = -2**31, 2**31 - 1


def wrap32(v):
    return (v - INT32_MIN) % 2**32 + INT32_MIN


def saturate32(v):
    return max(INT32_MIN, min(INT32_MAX, v))


x = INT32_MAX
print("x + 1:", x + 1)
print("wrapped to 32 bits:", wrap32(x + 1))
print("ctypes.c_int32(x + 1):", ctypes.c_int32(x + 1).value)
print("saturated to 32 bits:", saturate32(x + 1))
try:
    (x + 1).to_bytes(4, "big", signed=True)
except OverflowError as e:
    print("to_bytes in 4 bytes:", type(e).__name__)
Output
x + 1: 2147483648
wrapped to 32 bits: -2147483648
ctypes.c_int32(x + 1): -2147483648
saturated to 32 bits: 2147483647
to_bytes in 4 bytes: OverflowError
  • Verdict: idiom. Python's int never overflows, so a program that must act like a 32-bit type wraps, saturates or traps by hand.
  • ctypes.c_int32 keeps the low 32 bits of a value and does not check for overflow.
  • int.to_bytes traps: it raises OverflowError when the value does not fit in the bytes.
#include <algorithm>
#include <climits>
#include <cstdint>
#include <iostream>

int main() {
    unsigned u = UINT_MAX;
    std::cout << "UINT_MAX + 1: " << u + 1u << '\n';

    int x = INT_MAX;
    int r = 0;
    bool over = __builtin_add_overflow(x, 1, &r);
    std::cout << "__builtin_add_overflow(x, 1): " << (over ? "overflow" : "ok") << ", result " << r << '\n';

    std::int64_t wide = std::int64_t{x} + 1;
    std::int64_t lo = INT_MIN;
    std::int64_t hi = INT_MAX;
    std::cout << "saturated: " << std::clamp(wide, lo, hi) << '\n';
}
Output
UINT_MAX + 1: 0
__builtin_add_overflow(x, 1): overflow, result -2147483648
saturated: 2147483647
  • Verdict: stdlib. Unsigned arithmetic wraps, and signed overflow is undefined behavior. C++26 adds std::saturating_add and the other saturating operations in <numeric>. This example uses std::clamp on a wider type because GCC 13 does not have them.
  • __builtin_add_overflow is a GCC and Clang builtin, not standard C++.
JavaGitHub
public class Main {
  public static void main(String[] args) {
    int x = Integer.MAX_VALUE;
    System.out.println("x + 1: " + (x + 1));
    try {
      Math.addExact(x, 1);
    } catch (ArithmeticException e) {
      System.out.println("Math.addExact(x, 1): " + e.getClass().getSimpleName());
    }
    long wide = (long) x + 1;
    System.out.println("(long) x + 1: " + wide);
    System.out.println("saturated: " + Math.clamp(wide, Integer.MIN_VALUE, Integer.MAX_VALUE));
    System.out.println("Integer.MIN_VALUE / -1: " + Integer.MIN_VALUE / -1);
  }
}
Output
x + 1: -2147483648
Math.addExact(x, 1): ArithmeticException
(long) x + 1: 2147483648
saturated: 2147483647
Integer.MIN_VALUE / -1: -2147483648
  • Verdict: stdlib. The Java operators wrap, and Math.addExact, subtractExact, multiplyExact and negateExact throw ArithmeticException on overflow.
  • Math.clamp saturates a long to the int range. A wider type and a clamp is the usual way to saturate in Java.
#include <limits.h>
#include <stdio.h>

int main(void) {
    unsigned u = UINT_MAX;
    printf("UINT_MAX + 1: %u\n", u + 1u);

    int x = INT_MAX;
    int r = 0;
    int over = __builtin_add_overflow(x, 1, &r);
    printf("__builtin_add_overflow(x, 1): %s, result %d\n", over ? "overflow" : "ok", r);

    if (x > INT_MAX - 1) {
        printf("x + 1 would overflow\n");
    }

    long long wide = (long long)x + 1;
    int saturated = wide > INT_MAX ? INT_MAX : (int)wide;
    printf("saturated: %d\n", saturated);
    return 0;
}
Output
UINT_MAX + 1: 0
__builtin_add_overflow(x, 1): overflow, result -2147483648
x + 1 would overflow
saturated: 2147483647
  • Verdict: stdlib. Unsigned arithmetic wraps, and signed overflow is undefined behavior. C23 adds ckd_add, ckd_sub and ckd_mul in <stdckdint.h>. This example uses __builtin_add_overflow, the GCC and Clang builtin that does the same job, because older compilers do not have the header.
  • The test x > INT_MAX - 1 runs before the addition, so it never overflows.
  • A wider type gives the exact sum, and a compare saturates it.
using System;

int x = int.MaxValue;
Console.WriteLine($"unchecked(x + 1): {unchecked(x + 1)}");
try
{
    int y = checked(x + 1);
    Console.WriteLine(y);
}
catch (OverflowException e)
{
    Console.WriteLine($"checked(x + 1): {e.GetType().Name}");
}
long wide = (long)x + 1;
Console.WriteLine($"saturated: {Math.Clamp(wide, int.MinValue, int.MaxValue)}");
Output
unchecked(x + 1): -2147483648
checked(x + 1): OverflowException
saturated: 2147483647
  • Verdict: native. The checked and unchecked keywords choose the rule for an expression or a block. The default context is unchecked unless the project sets CheckForOverflowUnderflow.
  • Math.Clamp on a wider type saturates.
JavaScriptGitHub
const yesNo = (b) => (b ? "yes" : "no");
const max32 = 2147483647;
console.log(`max32 + 1: ${max32 + 1}`);
console.log(`(max32 + 1) | 0: ${(max32 + 1) | 0}`);

const safe = Number.MAX_SAFE_INTEGER;
console.log(`safe + 1 === safe + 2: ${yesNo(safe + 1 === safe + 2)}`);
console.log(`BigInt(safe) + 2n: ${BigInt(safe) + 2n}`);
console.log(`BigInt.asIntN(32, 2147483648n): ${BigInt.asIntN(32, 2147483648n)}`);

const addInt32 = (a, b) => {
  const sum = a + b;
  if (sum > max32 || sum < -max32 - 1) throw new RangeError("int32 overflow");
  return sum;
};
try {
  addInt32(max32, 1);
} catch (e) {
  console.log(`addInt32(max32, 1): ${e.name}`);
}
Output
max32 + 1: 2147483648
(max32 + 1) | 0: -2147483648
safe + 1 === safe + 2: yes
BigInt(safe) + 2n: 9007199254740993
BigInt.asIntN(32, 2147483648n): -2147483648
addInt32(max32, 1): RangeError
  • Verdict: idiom. A JavaScript number is a float, so a sum is rounded, not wrapped. The bitwise operators such as | 0 wrap a value to 32 bits.
  • Above Number.MAX_SAFE_INTEGER, two different sums can give the same number. BigInt grows, and BigInt.asIntN wraps on request.
package main

import (
	"errors"
	"fmt"
	"math"
)

func addInt32(a, b int32) (int32, error) {
	if (b > 0 && a > math.MaxInt32-b) || (b < 0 && a < math.MinInt32-b) {
		return 0, errors.New("int32 overflow")
	}
	return a + b, nil
}

func main() {
	var x int32 = math.MaxInt32
	fmt.Println("x + 1:", x+1)

	var u uint8 = 255
	fmt.Println("uint8 255 + 1:", u+1)

	_, err := addInt32(x, 1)
	fmt.Println("addInt32(x, 1):", err)
	sum, err := addInt32(x, -1)
	fmt.Println("addInt32(x, -1):", sum, err)
}
Output
x + 1: -2147483648
uint8 255 + 1: 0
addInt32(x, 1): int32 overflow
addInt32(x, -1): 2147483646 <nil>
  • Verdict: idiom. Go wraps signed and unsigned values and never panics on overflow. The standard library has no checked add for signed integers, so a program tests the operands before the operation.
  • The test compares with math.MaxInt32-b, which cannot overflow when b is positive.
RustGitHub
use std::num::Wrapping;

fn main() {
    let x = i32::MAX;
    println!("x.checked_add(1): {:?}", x.checked_add(1));
    println!("x.wrapping_add(1): {}", x.wrapping_add(1));
    println!("x.saturating_add(1): {}", x.saturating_add(1));
    println!("x.overflowing_add(1): {:?}", x.overflowing_add(1));
    let w = Wrapping(x) + Wrapping(1);
    println!("Wrapping(x) + Wrapping(1): {}", w.0);
    println!("(-5i32).checked_add(3): {:?}", (-5i32).checked_add(3));
}
Output
x.checked_add(1): None
x.wrapping_add(1): -2147483648
x.saturating_add(1): 2147483647
x.overflowing_add(1): (-2147483648, true)
Wrapping(x) + Wrapping(1): -2147483648
(-5i32).checked_add(3): Some(-2)
  • Verdict: native. The plain operators panic on overflow in debug builds. The checked_, wrapping_, saturating_ and overflowing_ methods choose a rule for one operation, and the Wrapping type makes the operators wrap.
  • The example does not use x + 1, because the compiler rejects an overflow that it can find at compile time.
  • Overflow in conversions. A conversion to a narrower type can lose the value too. See Type conversion.
  • The security weakness. An overflow that goes unnoticed can make a buffer too small. See Integer overflow or wraparound.
  • Two's complement. The wrapped result of a signed operation is the two's complement result. See Two's complement.
  • Detection with sanitizers. "UBSan (undefined behavior sanitizer) is available for C compilers."1 It reports signed overflow when the program runs.

Pitfalls

  • A check after the overflow in C or C++. A check such as if (a + b < a) for a signed a can be removed by the compiler, because signed overflow is undefined5. Check before the operation, or use ckd_add or a builtin.
  • Different builds, different results in Rust. A debug build panics, and a release build has no overflow checks by default, so it can wrap silently79. A test that runs only debug builds does not show what the release build does.
  • The most negative value. -INT_MIN and INT_MIN / -1 overflow. In C#, even an unchecked context can throw an ArithmeticException for int.MinValue / -14.
  • JavaScript rounding. A sum above Number.MAX_SAFE_INTEGER does not wrap and does not throw. It is rounded to a near float16.
  • Mean of two values. (a + b) / 2 can overflow when the mean fits. Wikipedia gives this as a common example: "Taking the arithmetic mean of two numbers by adding them and dividing by two"1. When a and b are both 0 or more and a <= b, use a + (b - a) / 2.

Cost

Wrapping costs nothing, because it is what the adder does. A trap or a check adds a test of the overflow flag after the operation, which is a branch that is nearly always not taken. The cost of checks is the reason that Cargo turns them off in the release profile by default9. Saturation needs a compare and a select in software, but some processors have it in hardware: saturation "was one of the extensions made by the Intel MMX extension, specifically for such signal-processing applications."12 Growth has the highest cost, because each value can need memory on the heap.

History

Overflow has caused well-known failures. "An unhandled arithmetic overflow in the engine steering software was the primary cause of the crash of the 1996 maiden flight of the Ariane 5 rocket."1 In 2015, the U.S. Federal Aviation Administration said that it would order Boeing 787 operators to reset the electrical system periodically, "to avoid an integer overflow which could lead to loss of electrical power and ram air turbine deployment"1. Wikipedia says that "In Java 8, there are overloaded methods, for example Math.addExact(int, int)"1. The standard checked operations of C came in C23 with <stdckdint.h>19, and saturating operations come to C++ in C++2614.

References

  1. Integer overflow, Wikipedia, the introduction; Inconsistent behavior; Integer overflow handling in various programming languages; Detection; Examples
  2. The Go Programming Language Specification, Integer overflow
  3. The Java Language Specification, Java SE 27 Edition, Chapter 4: Types, Values, and Variables, 4.2.2 Integer Operations
  4. Arithmetic operators, C# reference, Microsoft Learn, Arithmetic overflow and division by zero, Integer arithmetic overflow
  5. Arithmetic operators, C reference, cppreference.com, Overflows
  6. Options for Code Generation Conventions, Using the GNU Compiler Collection (GCC), -ftrapv; -fwrapv
  7. Behavior not considered unsafe, The Rust Reference, Integer overflow
  8. Operator expressions, The Rust Reference, Overflow
  9. Profiles, The Cargo Book, overflow-checks; Default profiles, dev and release
  10. C# Compiler Options for language feature rules, Microsoft Learn, CheckForOverflowUnderflow
  11. Math, Java SE 27 API, addExact
  12. Saturation arithmetic, Wikipedia, the introduction; Implementations
  13. i32, Rust standard library, checked_add; wrapping_add; overflowing_add; saturating_add
  14. std::saturating_add, C++ reference, cppreference.com, the synopsis and the description
  15. Built-in Types, Python 3 documentation, Numeric Types, int, float, complex
  16. Number.MAX_SAFE_INTEGER, MDN Web Docs, the description and the example
  17. BigInt.asIntN(), MDN Web Docs, the description
  18. Numeric Types, PostgreSQL documentation, 8.1.1 Integer Types
  19. ckd_add, C reference, cppreference.com, the synopsis and the description
  20. Built-in Functions to Perform Arithmetic with Overflow Checking, Using the GNU Compiler Collection (GCC), __builtin_add_overflow
  21. about_Arithmetic_Operators, PowerShell documentation, Microsoft Learn, Adding and multiplying non-numeric types; the type of the result

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/JV2T7E/text.yaml