liveBook · Manning

Numerical overflow

As explained in 100 Go Mistakes and How to Avoid Them

Integer overflow is the condition in which an integer operation produces a result outside the representable range of the integer type.

Integer overflow occurs when arithmetic produces a value outside an integer type’s representable range. Go rejects detectable constant overflow at compile time but handles run-time overflow and underflow silently, allowing surprising negative or wrapped results. section 3.2.1

Incrementing past math.MaxInt32

var counter int32 = math.MaxInt32 counter++ fmt.Printf("counter=%d\n", counter) The increment does not panic; counter becomes -2147483648. The sign bit changes because no positive value remains representable in 32 bits. section 3.2.1

Prevent silent failures by checking the operation before or after it:

  • For increment, compare the value with the type limit: math.MaxInt32, math.MaxInt, or math.MaxUint. section 3.2.2
  • For addition, test whether a > math.MaxInt-b before evaluating a+b. section 3.2.3
  • For multiplication, handle zero, one, and math.MinInt specially, then verify that result/b still equals a. section 3.2.4
  • Use math/big when an int cannot represent the required values. section 3.2.4

Signed integers

Unsigned integers

int8 (8 bits)

uint8 (8 bits)

int16 (16 bits)

uint16 (16 bits)

int32 (32 bits)

uint32 (32 bits)

int64 (64 bits)

uint64 (64 bits)

Compare signed and unsigned integer widths before choosing a type or its overflow boundary. section 3.2.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines signed representation and supplies checks for increment, addition, and multiplication, but does not cover every arithmetic operation.
Examples
Uses an int32 counter, boundary-guard functions, addition guards, and multiplication validation.
What it assumes
Assumes familiarity with Go integers and arithmetic while defining representable ranges and signed binary representation.
What you can do after
Diagnose overflow risks and implement guards for increment, addition, and multiplication.
How it connects
Connects integer types, underflow, two’s complement, arithmetic operations, and arbitrary-precision arithmetic.

Also explained in

Compare how 7 books explain numerical overflow →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.