0

For Golang code:


import "fmt"

func main() {
    var a uint8 = 1
    var b uint8 = 1
    fmt.Printf("%T %v %b\n", uint32(a^b)-1, uint32(a^b)-1, uint32(a^b)-1)
    fmt.Printf("%T %v %b\n", uint32(uint8(0))-1, uint32(uint8(0))-1, uint32(uint8(0))-1)
}

When I run the above code, what I expect to see is, for both

fmt.Printf("%T %v %b\n", uint32(a^b)-1, uint32(a^b)-1, uint32(a^b)-1)

and

fmt.Printf("%T %v %b\n", uint32(uint8(0))-1, uint32(uint8(0))-1, uint32(uint8(0))-1),

there should be constant -1 overflows uint32 error.

The actual execution result:

fmt.Printf("%T %v %b\n", uint32(a^b)-1, uint32(a^b)-1, uint32(a^b)-1) executed successfully.

fmt.Printf("%T %v %b\n", uint32(uint8(0))-1, uint32(uint8(0))-1, uint32(uint8(0))-1) caused constant -1 overflows uint32 error.

Could someone help explain this? Thanks!

  • 4
    The code of the 1st line deals with variables, wihich have [defined rules for overflow](https://go.dev/ref/spec#Integer_overflow) _at runtime_ while the second line deals purely with constants, and all calculations there are performed at compile time, using a [different set of rules](https://go.dev/ref/spec#Constants); also see [this](https://blog.golang.org/constants). – kostix Feb 18 '22 at 08:55
  • 2
    …To say that in other words: integers at runtime can overflow, in defined way. Typed constants cannot overflow as it's checked by the compiler which evaluates [constant expressions](https://go.dev/ref/spec#Constant_expressions) in your code. – kostix Feb 18 '22 at 08:59

0 Answers0