This question already has an answer here:
Does Go compiler's evaluation differ for constant expression and other expression

(1个答案)


2年前关闭。



func main() {
   var a = math.MaxInt64
   fmt.Println(a + 1)             //-9223372036854775808
   fmt.Println(math.MaxInt64 + 1) //constant 9223372036854775808 overflows int
}

why the two ways perform differently?

最佳答案

在第二个示例中,math.MaxInt64 + 1是一个常量表达式,在编译时进行计算。 spec说:



但是,当将表达式的值传递给fmt.Println时,必须将其转换为实际的预先声明的类型,在这种情况下,int表示为带符号的64位整数,该整数不能表示常量。



在第一个示例中,a + 1不是常量表达式,而是常规算法,因为a被声明为变量,因此常量表达式math.MaxInt64转换为int。等同于:

var a int = math.MaxInt64

普通算术允许溢出:



通过较小的修改,您可以使示例相同:
func main() {
    const a = math.MaxInt64
    fmt.Println(a + 1)             //constant 9223372036854775808 overflows int
    fmt.Println(math.MaxInt64 + 1) //constant 9223372036854775808 overflows int
}

关于go - Golang溢出int64可以直接操作,但不能事先分配一个值? [复制],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50146093/

10-14 14:47
查看更多