A game's Int32 score counter crashes after a very long session; what does Swift do on integer overflow, and when is `&+` the right fix?
answer
- checked arithmetic, not silent wrap
- constant folding catches literals
- ampersand opts into wrapping
- ReportingOverflow returns a flag
basics
~20 sSwift's +, - and * trap at run time on overflow, and the compiler rejects overflows it can compute. &+, &- and &* wrap in two's complement: right for hashes and checksums, wrong for a score, which should clamp or use a wider type.
solid answer
~40 sUnlike C, Swift's arithmetic operators are checked: when `score + points` does not fit in `Int32`, the process traps instead of continuing with a garbage value. The check stays on in `-O` release builds; only `-Ounchecked` removes it. When the compiler can compute the operands, overflow is a compile error, such as "arithmetic operation '127 + 1' (on type 'Int8') results in an overflow". The overflow operators `&+`, `&-` and `&*` opt into wrapping: `Int32.max &+ 1` is `Int32.min`, and that result is fully defined. Wrapping fits hash mixing, checksums and sequence numbers; for a score it silently turns a high score negative. There the fix is a wider type, or `addingReportingOverflow(_:)` plus clamping to `.max`, because the standard library has no saturating operator.
code
swift · 23 linesstruct ScoreCounter {
private(set) var value: Int32 = 0
// Traps at run time when value + points does not fit in Int32.
mutating func addTrapping(_ points: Int32) {
value += points
}
// The standard library has no saturating operator: read the
// overflow flag and clamp instead of crashing.
mutating func addClamped(_ points: Int32) {
let (sum, overflow) = value.addingReportingOverflow(points)
value = overflow ? (points > 0 ? .max : .min) : sum
}
}
var counter = ScoreCounter()
counter.addClamped(.max)
counter.addClamped(10)
print(counter.value) // 2147483647
print(Int32.max &+ 1) // -2147483648: wraps, never traps
counter.addTrapping(1) // traps: arithmetic overflow at run time
print("unreachable")go deeper
Recall that plain + traps on overflow instead of wrapping, and that the ampersand operators exist for deliberate wrapping.
Explain compile-time folding versus the run-time trap, two's-complement wrapping with &+, &- and &*, and the ReportingOverflow methods that return a flag.
Choose per value: wrap for hashes and checksums, clamp or widen for counters users see, and know that -O keeps the check while -Ounchecked drops it.
Decide where overflow is a bug worth crashing on and where it is domain behaviour, and keep wrapping sites explicit and reviewed rather than sprinkling &+ for speed.
## Checked arithmetic by default In Swift, the ordinary arithmetic operators `+`, `-` and `*` on integer types are **checked**. When the mathematical result does not fit in the type, for example an `Int32` score passing `Int32.max` (2,147,483,647), the program **traps**: it stops immediately instead of continuing with a wrong value. The Swift book states the design directly: unlike the arithmetic operators in C and Objective-C, Swift's arithmetic operators don't allow values to overflow by default. The trap is deliberate. A silently wrapped score turns a record high into a large negative number that then flows into saving, sorting and the leaderboard. A crash with a stack trace points at the exact line. ## Compile time versus run time Where the overflow is detected depends on what the compiler can see: | Situation | What happens | |---|---| | `let small: Int8 = 127 + 1` | Compile error: `arithmetic operation '127 + 1' (on type 'Int8') results in an overflow` | | `let x: UInt8 = 0 - 1` inside a function | Compile error: `arithmetic operation '0 - 1' (on type 'UInt8') results in an overflow` | | `score += points` with values known only at run time | Compiles; traps when the sum overflows | | `10 / 0` | Compile error: `division by zero` | | `Int.min / -1` or a zero divisor at run time | Traps | The compile-time errors come from constant folding: when the compiler can compute both operands, a provable overflow becomes an error. Anything that depends on input, a file or a server response is checked at run time. The check is not a debug-only feature: - `-Onone` (Debug) traps on overflow. - `-O` (the usual Release setting) still traps; the message text may be omitted, but the process stops. - `-Ounchecked` removes the check, so the overflow is no longer caught. Few apps should ship with it. ## The overflow operators When wrapping is what you want, opt in explicitly with the **overflow operators**, which all start with `&`: - `&+` overflow addition: `Int32.max &+ 1` is `Int32.min`. - `&-` overflow subtraction: `UInt8.min &- 1` is 255. - `&*` overflow multiplication: keeps the low bits of the product. Their results are fully defined two's-complement wrapping, not undefined behaviour, and they skip the overflow check, which matters in hot loops. There is no `&/`; division has no wrapping operator. Wrapping is correct where the arithmetic is meant to be modular: - hash mixing and checksums, as in the second example; - sequence numbers and ring counters designed to roll over; - bit-level codecs that work modulo 2^n. ## Detecting overflow without trapping To know that an overflow happened without crashing, every fixed-width integer type offers reporting methods that return a tuple `(partialValue, overflow)`: 1. `addingReportingOverflow(_:)` 2. `subtractingReportingOverflow(_:)` 3. `multipliedReportingOverflow(by:)` 4. `dividedReportingOverflow(by:)`, where dividing by zero is not an error and returns `(x, true)` 5. `remainderReportingOverflow(dividingBy:)` For addition, subtraction and multiplication, `partialValue` is the wrapped result, the same value the matching `&` operator gives, and `overflow` is a `Bool` you can branch on. The standard library has no saturating operator, so clamping is written by hand from this flag. ## Fixing the score counter For a counter a player sees, wrapping is the wrong fix. In order of preference: 1. **Make overflow impossible**: store the score in a type wide enough for any real session, such as `Int64`. Choosing widths and converting between them belongs with numbers and numeric conversion. 2. **Clamp**: use `addingReportingOverflow(_:)` and pin the value at `.max`, as the first example does, if the type must stay `Int32` for storage or a wire format. 3. **Wrap** with `&+` only if a rolled-over score is genuinely acceptable, which for a score it rarely is. The rule of thumb: plain operators for quantities that must be right, `&` operators for arithmetic that is modular by design, and reporting methods when you need to decide at run time.
- Does the overflow check disappear in a Release build?No. Release builds normally use `-O`, which keeps the check, so the overflow still traps, though the message may not be printed. Only `-Ounchecked` removes the check, after which the overflow is no longer caught. That setting trades safety for speed and few apps should ship with it.
- Why does `let x: UInt8 = 0 - 1` fail to build when the same subtraction on a value read at run time only traps?The compiler folds arithmetic on values it can compute, such as literals and constants it can propagate, and turns a provable overflow into the error "arithmetic operation '0 - 1' (on type 'UInt8') results in an overflow". A value read at run time cannot be folded, so a check is compiled in and traps when it fires.
- Is there a non-trapping form of integer division?There is no `&/` operator. Plain `/` traps on a zero divisor and on `Int.min / -1`. `dividedReportingOverflow(by:)` returns `(partialValue, overflow)` instead, and its documentation states that dividing by zero is not an error there: `x.dividedReportingOverflow(by: 0)` is `(x, true)`.
The overflow operators behave like a car's odometer rolling from 999999 back to 000000; Swift's plain + is a meter that stops the car rather than display a wrong reading.
- Integer overflow in Swift wraps around silently, as it does in C
- Overflow checks only run in Debug builds
- &+ skips work but still traps when the sum overflows
- The compiler catches every integer overflow at build time
- Switching the score to &+ is a safe way to stop the crash
- Swift offers &/ for wrapping division