`unchecked-add-int` adds two numbers using 32-bit signed integer arithmetic. It is useful when an algorithm needs `int` results rather than Clojure’s usual `long` arithmetic, as in hashing or integer-based image processing. section 5.14
Its contract is narrow:
- It takes exactly two numeric arguments within the signed `int` range and casts them to primitive `int` values. section 5.14
- It returns an `int` result without checking for overflow. A result beyond `Integer/MAX_VALUE` rolls over to the negative end of the range. section 5.14 section 5.1
Casting and rollover
`(unchecked-add-int 2.0 1)` returns `3`; `(type (unchecked-add-int 2.0 1))` returns `java.lang.Integer`. By contrast, `(unchecked-add 2.0 1)` returns `3.0`. At the boundary, `(unchecked-add-int Integer/MAX_VALUE 1)` returns `Integer/MIN_VALUE`. section 5.14 section 5.1
Choose `unchecked-add-int` when 32-bit results and possible rollover are intentional. Ordinary `+` checks for overflow and promotes `int` operands to `long`; the unchecked operators without the `-int` suffix do not force an `int` result. Related functions provide unchecked subtraction, multiplication, division, increment, decrement, negation, and remainder on `int` values. section 5.5 section 5.14
| 32 bits |
decimal value |
relative value |
|
|
2147483645 |
(- Integer/MAX_VALUE 2) |
|
|
2147483646 |
(- Integer/MAX_VALUE 1) |
|
|
2147483647 |
Integer/MAX_VALUE, (unchecked-subtract-int Integer/MIN_VALUE 1) |
|
|
-2147483648 |
Integer/MIN_VALUE, (unchecked-add-int Integer/MAX_VALUE 1) |
|
|
-2147483647 |
(+ Integer/MIN_VALUE 1) |
|
|
-2147483646 |
(+ Integer/MIN_VALUE 2) |
The 32-bit value table shows the sign change when adding one to the largest signed `int`. section 5.1
