Go

How does Go handle integer overflow, division, and conversions between numeric types?

Question 34HardGo 1.22 to 1.25
var x int8 = 127
x++
fmt.Println(x) // -128: signed overflow wraps (two's complement), no panic

var u uint8 = 0
u--
fmt.Println(u) // 255

fmt.Println(-7 / 2, -7 % 2) // -3 -1: division truncates toward zero

lo := int64(math.MinInt64)
fmt.Println(lo / -1)      // -9223372036854775808: overflow wraps, no panic

fmt.Println(int8(300 & 0xFF)) // 44
big := 300
fmt.Println(int8(big))      // 44: conversion keeps the low bits
neg := -1
fmt.Println(uint32(neg))    // 4294967295: conversion reinterprets the bits

// const c int8 = 128       // compile error: constant 128 overflows int8
// _ = 1 / 0                // compile error: division by zero
zero := 0
// _ = 1 / zero             // runtime panic: integer divide by zero
fmt.Println(1.0 / float64(zero)) // +Inf: float division by zero doesn't panic

Rules:

  • Integer arithmetic at run time wraps around silently, for both signed and unsigned types. The spec defines this behavior, unlike C, where signed overflow is undefined.
  • Constant expressions are checked at compile time, so overflow there is an error.
  • Integer division by zero panics at run time. Float division by zero gives ±Inf or NaN.
  • % takes the sign of the dividend.
  • Shifting by a negative amount panics. Shifting by at least the bit width gives 0 (or -1 for right shifts of negative signed values).

For overflow-safe code, check before you add, or use math/bits.Add64 and Mul64, or math/big. int is 64-bit on 64-bit platforms, but don't assume that when data is serialized. Use fixed-size types in file formats and wire protocols.

More on Language Fundamentals & Types

All 39 Language Fundamentals & Types questions