提问人:mercuryRising 提问时间:11/17/2023 最后编辑:iczamercuryRising 更新时间:11/17/2023 访问量:67
golang 有 int32 溢出吗?[复制]
Does golang have int32 overflow? [duplicate]
问:
func overFlowTest() {
maxInt32 := math.MaxInt32
overflowedValue := maxInt32 + 1
fmt.Println("Max Int32:", maxInt32)
fmt.Println("Overflowed Value:", overflowedValue)
fmt.Printf("Type of overflowedValue is %T\n", overflowedValue)
}
结果如下:
最大 Int32:2147483647
溢出值:2147483648
overflowedValue 的类型为 int
当我尝试maxInt64时,它溢出了。这是否意味着当 int32 溢出时,它会自动转换为 int64?
答:
3赞
icza
11/17/2023
#1
数学。MaxInt32
是一个非类型化常量:
const MaxInt32 = 1<<31 - 1 // 2147483647
如果您在简短的变量声明中使用它而没有显式提供类型:
maxInt32 := math.MaxInt32
将使用非类型化整数常量的默认类型,即:int
fmt.Printf("Type of maxInt32 is %T\n", maxInt32) // Prints int
非类型化常量具有默认类型,该类型是在需要类型化值的上下文中(例如,在没有显式类型的简短变量声明中)隐式转换为常量的类型。非类型化常量的默认类型分别为 、 、 、 或,具体取决于它是布尔常量、符文常量、整数常量、浮点常量、复杂常量还是字符串常量。
i := 0
bool
rune
int
float64
complex128
string
的大小取决于架构,它在 Go Playground 上是 64 位的。因此,加到 不会以 64 位整数溢出。int
1
MaxInt32
如果修改示例以使用 type:int32
maxInt32 := int32(math.MaxInt32)
输出将是(在 Go Playground 上尝试):
Max Int32: 2147483647
Overflowed Value: -2147483648
Type of overflowedValue is int32
Type of maxInt32 is int32
推荐阅读:Go 博客:常量
评论