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
