Search code examples
gobit-shift

How does 1 << 64 - 1 work?


At http://tour.golang.org/#14 they show an example where the number 1 is shifted by 64 bits. This of course would result in an overflow, but then it is subtracted by 1 and all is well. How does half of the expression result in a failure while the entire expression as whole work just fine?

Thoughts:
I would assume that the setting of the unsigned to a number larger than what it allows is what causes the explosion. It would seem that memory is allocated more loosely on the right hand side of the expression than on the left? Is this true?


Solution

  • The result of your expression is a (compile time) constant and the expression is therefore evaluated during compilation. The language specification mandates that

    Constant expressions are always evaluated exactly; intermediate values and the constants themselves may require precision significantly larger than supported by any predeclared type in the language. The following are legal declarations:

    const Huge = 1 << 100         // Huge == 1267650600228229401496703205376  (untyped integer constant)
    const Four int8 = Huge >> 98  // Four == 4                                (type int8)
    

    https://golang.org/ref/spec#Constant_expressions