Overflow Guards Around Integer Arithmetic

Guard integer addition and multiplication against wraparound with range checks and divide-back verification so bad inputs fail loudly.

GoData Integrity

Code

gosnippet
49 lines
package main

import (
	"fmt"
	"math"
)

// addInts 在相加前做区间判断:两步都落在 int 范围内才执行
func addInts(a, b int) (int, error) {
	if b > 0 && a > math.MaxInt-b {
		return 0, fmt.Errorf("add overflows: %d+%d", a, b)
	}
	if b < 0 && a < math.MinInt-b {
		return 0, fmt.Errorf("add underflows: %d+%d", a, b)
	}
	return a + b, nil
}

// mulInts 先乘后回除校验:结果回除其中一个因子必须还原出另一个
func mulInts(a, b int) (int, error) {
	if a == 0 || b == 0 {
		return 0, nil
	}
	result := a * b
	if result/b != a {
		return 0, fmt.Errorf("mul overflows: %d*%d", a, b)
	}
	return result, nil
}

func main() {
	for _, pair := range [][2]int{{1_000_000, 42}, {math.MaxInt, 1}, {math.MinInt, -1}} {
		sum, err := addInts(pair[0], pair[1])
		if err != nil {
			fmt.Println("add:", err)
		} else {
			fmt.Println("add:", sum)
		}
	}

	for _, pair := range [][2]int{{12345, 67}, {math.MaxInt, 2}, {-3, math.MinInt}} {
		product, err := mulInts(pair[0], pair[1])
		if err != nil {
			fmt.Println("mul:", err)
		} else {
			fmt.Println("mul:", product)
		}
	}
}

How the code behaves

The working parts are the functions addInts, mulInts and main.

The file repeats itself only inside for _, pair := range [][2]int{{1_000_000, 42}, {math.MaxInt, 1}, {math.MinInt, -1}}. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.

Points of care

  • Nothing to set up: the platform already ships every API used.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Applying it

The entry-point signature is func addInts(a, b int) (int, error)

The run prints add:, mul: — each prefix names the step that produced it.

main sequences addInts and mulInts; executing the file runs that flow once.

Statements that matter

return 0, fmt.Errorf("add underflows: %d+%d", a, b)
return 0, fmt.Errorf("add overflows: %d+%d", a, b)
return 0, fmt.Errorf("mul overflows: %d*%d", a, b)

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
No exceptions — `error` returns checked at 2 sites, and callers branch on `err` first.
What does Overflow Guards Around Integer Arithmetic print when run?
Running the file directly is enough — expect labeled output lines such as `add:`, `mul:`.