Recognize overflow and rounding
Recognize overflow and rounding
Fixed-width integers have limited ranges. Go unsigned arithmetic wraps modulo 2 raised to the width; signed integer operations may overflow with a deterministic result defined by the signed representation and operation. Overflow of a runtime integer does not automatically panic. Constants that cannot be represented in their required type are rejected during compilation.
package main
import "fmt"
func main() { var count uint8 = 255 count++ fmt.Println(count) var temperature int8 = 127 temperature++ fmt.Println(temperature)}The uint8 count wraps to zero; the int8 value wraps to -128. The constant expression uint8(255) + 1 is invalid instead. Use a wider type or check the permitted range before the operation. For example, a uint8 counter can be incremented safely only when it is below 255.
Floating-point precision
package main
import "fmt"
func main() { a := 0.1 b := 0.2 sum := a + b fmt.Printf("%.17g\n", sum) fmt.Println(sum == 0.3) fmt.Println(0.1+0.2 == 0.3)}The variables are float64 values, so the addition uses rounded binary operands. %.17g prints up to 17 significant digits. The constant comparison in the final line is evaluated as a constant expression and is true. Do not expect exact decimal arithmetic from runtime floats; choose an appropriate tolerance for measured values or integer smallest units for exact amounts. A tolerance is problem-specific, not a universal constant.
Try it locally
Use uint8 count = 250, add 10 and print it. Repeat with uint16 wide = 250. Expected: 4 260. Explain to yourself why only one wraps.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expressions and Arithmetic 08: Recognize overflow and rounding
Check the lesson objective before moving on.
What happens when a uint8 variable holding 255 is incremented?
Why may a float64 sum of 0.1 and 0.2 differ from 0.3?