How is it still possible to calculate 164-1, without issuing an overflow?

1

The limit of uint64 is (2 ^ 64) -1, or simply 1

asked by anonymous 04.04.2018 / 00:15

2 answers

2

Note that there is an optimization and the compiler folda all this for the result number and does not execute anything, it is the same as writing the literal number, which is always a constant. If you put a simple variable already coiled:

package main
import "fmt"

func main(){
    x := uint32(64)
    fmt.Print(uint64(1 << 65 - 1 << x - 1))
}

See not working on ideone . And in Coding Ground . Also put it in GitHub for future reference .

So by transforming it into a constant value it is possible to work in this way according to the specification , which I consider a mistake because it changes semantics for no apparent reason, hence the question is very pertinent. It should have a reason, but for me constant it should have the same semantics of the variable except for the fact that its value never changes and allows some optimization.

    
04.04.2018 / 01:09
1

This is because the 1<<65-1<<64-1) value is not treated as a uint64 during execution, but as a Constant Expression during compilation, and may contain only Constants .

According to the specification:

  

Constant expressions are always exactly; intermediate values   and the constants themselves may require precision   larger than supported by any predeclared type in the language.

Free translation:

  

Constant Expressions are always calculated exactly; intermediate values and the constants themselves may require a   significantly higher than any type declared by the   language.

According to the language specification, such constants (integer type) must be represented with at least 256 bits. The current version of the language supports accuracy up to 512 bit 512 bit . If an operation that exceeds this limit is performed, an error will be thrown. Example:

fmt.Print(uint64(1 << 512))

The above excerpt generates the following error: shift count too large: 512 .

If the result of Constant Expression is a value greater than the one supported or different from the declared type, the compiler will identify this as an error.

    
04.04.2018 / 01:21