Overflow error when converting negative int64 to uint64 in one liner

2,052 views
Skip to first unread message

Ugorji Nwoke

unread,
Apr 16, 2013, 11:08:51 PM4/16/13
to golan...@googlegroups.com
http://play.golang.org/p/WSqe7NtkiW

Why can I do:
var x int64 = -1
var y uint64 = uint64(x)

But cannot do:
var y2 uint64 = uint64(int64(-1))

For the second one, I get:
constant -1 overflows uint64

Is this a bug? I spent a while trying to figure out why I was getting the error. From my limited understanding, it seems that the conversion first to an int64 is stripped out when done on one line.


David Symonds

unread,
Apr 16, 2013, 11:15:01 PM4/16/13
to Ugorji Nwoke, golan...@googlegroups.com
Sounds like a bug to me. File something on the issue tracker.

Ugorji Nwoke

unread,
Apr 16, 2013, 11:19:53 PM4/16/13
to golan...@googlegroups.com, Ugorji Nwoke

Daniel Theophanes

unread,
Apr 16, 2013, 11:36:37 PM4/16/13
to golan...@googlegroups.com
The first case happens at run-time. The compiler doesn't try to prove every path.
The second case is evaluated at compile time. When the compiler evaluates constants, it does checks like these even if their run-time behavior is different.

Ugorji Nwoke

unread,
Apr 16, 2013, 11:40:19 PM4/16/13
to golan...@googlegroups.com, Ugorji Nwoke
David just responded to the issue, and it seems this has to do with typed constants. 

var v int64 = -1 // v is now a variable
var v2 uint64 = uint64(v) // converting a variable of type int64 to uint64 is allowed, 

var v2 uint64 = uint64(int64(-1)) // the int64(-1) is a typed constant, and cannot legally be converted to a uint64 

This and other examples are in the spec at: http://tip.golang.org/ref/spec#Constant_expressions

So this doesn't seem like a bug. 

Thanks David.
Reply all
Reply to author
Forward
0 new messages