liveBook · Manning

Unchecked-add

As explained in Clojure: The Essential Reference

unchecked-add is a Clojure numeric function that performs addition without overflow checking or automatic promotion.

unchecked-add performs numeric addition with Java-style unchecked overflow behavior. It accepts exactly two numeric arguments, returns their sum, and avoids the overflow checks used by ordinary arithmetic operators. section 5.13 section 5.5

Use unchecked-add when the performance benefit is worth allowing wraparound:

  • Pass exactly two numeric values; unlike +, unchecked-add does not accept multiple arguments. section 5.13
  • Expect the result type to follow the most contagious, or precise, operand type. section 5.13
  • Prefer ordinary + or an auto-promoting operator when overflow must be detected or precision preserved. section 5.5

Addition and signed-long wraparound

(unchecked-add 1 2) ;; 3 (unchecked-add 9223372036854775807 1) ;; -9223372036854775808 The second result wraps from the largest signed long to the smallest instead of promoting or throwing an overflow exception.

Hashing with intentional overflow

Unchecked addition composes with unchecked multiplication in a rolling hash. Overflow supplies the fixed-width wraparound behavior while processing successive characters.

Listing 5.10. → Math, Overflowing Operators, Integer Math
(unchecked-add [x y])

(unchecked-subtract [x y])

(unchecked-multiply [x y])

(unchecked-inc [x])

(unchecked-dec [x])

(unchecked-negate [x])

Compare unchecked-add with the related unchecked subtraction, multiplication, increment, decrement, and negation functions. section 5.13

How Clojure: The Essential Reference covers it

How deep it goes
Explains arity, result-type contagion, overflow wraparound, performance trade-offs, and a hashing application.
Examples
Demonstrates basic addition, signed-long wraparound, and a string hash built from unchecked addition and multiplication.
What it assumes
Assumes familiarity with Clojure function invocation, numeric types, and ordinary arithmetic operators.
What you can do after
Apply unchecked-add in performance-sensitive Clojure numeric code when overflow wraparound is acceptable.
How it connects
Connects unchecked-add to Clojure arithmetic operators, integer overflow, type promotion, Java longs, and hashing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.