Choose integer widths and handle overflow
Choose integer widths and handle overflow
Fixed-width integers have defined ranges; int depends on the target architecture. Runtime unsigned arithmetic wraps modulo 2 to the power of the width. Check range before narrowing or adding when wrapping is unwanted.
package main
import ( "fmt")
func main() { x := uint8(255) x++ fmt.Println(x)}The variable wraps from 255 to zero. A constant declaration const x uint8 = 256 does not compile. Signed overflow is also defined by Go and does not automatically panic.
Expected output:
0Guard an addition
package main
import ( "fmt" "math")
func add(a, b uint64) (uint64, bool) { if b > math.MaxUint64-a { return 0, false } return a + b, true}func main() { fmt.Println(add(12, 30)) fmt.Println(add(math.MaxUint64, 1))}For unsigned values, subtract a from the maximum to find remaining room. The boolean reports whether the sum fits. Do not first perform an overflowing sum.
Expected output:
42 true0 falseTry it locally
Check whether 300 and 42 can fit in uint8.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric engineering 01: Choose integer widths and handle overflow
Check the lesson objective before moving on.
What does a uint8 variable become after incrementing 255?
When should narrowing be checked?