Checking Addition Before Storing a Narrow Result
A calculation can fit in its working representation and still exceed the field where it will be written.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a short sum
Adding 120 and 20 gives 140. Both inputs fit a signed eight-bit integer but the sum exceeds 127. A wider intermediate lets the program detect that before narrowing. See two's complement for the signed range.
Check the desired failure
A validator may reject the input pair or store a saturated value under a documented rule. Test a pair summing to exactly 127 and another summing to 128. Boundary tests distinguish the two outcomes.[1]
Verify against the target range before conversion
Two unsigned byte values 220 and 60 sum to 280. Converting the result modulo 256 yields twenty-four, losing the overflow information. Compute in a wider exact type or check \(b\le255-a\) for nonnegative byte operands before adding. See unsigned ranges.
a=220, b=60: remaining capacity 35 → reject
a=220, b=35: sum 255 → accept
a=0, b=0: sum 0 → accept
Include intermediate type behavior in the check
A narrow arithmetic expression might already overflow before a later range test. Widen before the operation when that is the chosen remedy. For signed values, positive and negative bounds require separate reasoning.