liveBook · Manning

Unchecked-inc

As explained in Clojure: The Essential Reference

unchecked-inc is a Clojure function that increments a numeric value without checking for numeric overflow.

unchecked-inc increments one numeric value without checking for integer overflow. It returns the corresponding result, with numeric behavior determined by the operand’s type. section 5.13 section 5.6

Use unchecked-inc when these contract and edge-case rules are acceptable:

  • Pass exactly one numeric argument; unlike unchecked-add, unchecked-inc does not accept multiple operands. section 5.13
  • Expect ordinary increments such as (unchecked-inc 100) producing 101. section 5.13
  • Expect a signed long overflow to wrap around rather than promote or throw: incrementing Long/MAX_VALUE produces Long/MIN_VALUE. section 5.6 section 5.13
  • Choose inc' when overflow should promote to BigInt, or unchecked-inc-int when Integer-width behavior is required. section 5.6

Overflowing at the long boundary

(unchecked-inc Long/MAX_VALUE) ;; -9223372036854775808 The operation crosses the upper signed-long boundary and resumes at the lower boundary with the sign changed. section 5.6

Using unchecked-inc in a loop

(defn faster [n] (loop [n (int n) i 0] (if (< i n) (recur n (unchecked-inc i)) i))) A benchmark compares this loop with one using inc and reports lower mean execution time for the unchecked version. section 5.6

(unchecked-inc (long (Math/pow 2 63))) ; #1
;; -9223372036854775808

(unchecked-dec (long (- (Math/pow 2 63)))) ; #2
;; 9223372036854775807

Browse paired boundary examples showing unchecked increment and decrement wraparound for signed long values. section 5.13

How Clojure: The Essential Reference covers it

How deep it goes
Defines arity, numeric results, overflow wraparound, alternatives, and a benchmark, but does not detail implementation internals.
Examples
Demonstrates ordinary incrementing, signed-long wraparound, and loop benchmarking against inc.
What it assumes
Assumes numeric inputs and teaches the signed-long boundary, overflow consequences, and related increment variants through examples.
What you can do after
Apply unchecked-inc in numeric code and recognize when its wraparound differs from checked or auto-promoting increment.
How it connects
Connects unchecked-inc with inc, inc', unchecked-dec, unchecked-inc-int, integer overflow, numeric types, 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.