www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - excessively long integer literal

reply Ap Lee <aplee primus.ca> writes:
Hello,

I am trying to build some template struct for large integer values, and I 
realized there is something weird with the lexical interpretation of 
integer literals.

I have this code instantiating a LargeInt struct which, in this example, 
has a capacity of 256 bits:

   LargeInt!(256) v = 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF;

Under the hood, this assignment uses the opAssign overload I created for 
ulong. Obviously, ulong is only 64 bits in size, and only the lowest 64 
bits of the "v" variable get set to 1, while the upper bits remain at 0.

But there is something wrong. The compiler accepted this code, and it's 
silently wrong at runtime... I think the compiler should have rejected the 
integer literal.

What do you think?

Ap
Jan 06 2008
parent Robert DaSilva <sp.unit.262+digitalmars gmail.com> writes:
Ap Lee wrote:
 Hello,
 
 I am trying to build some template struct for large integer values, and
 I realized there is something weird with the lexical interpretation of
 integer literals.
 
 I have this code instantiating a LargeInt struct which, in this example,
 has a capacity of 256 bits:
 
   LargeInt!(256) v = 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF;
 
 Under the hood, this assignment uses the opAssign overload I created for
 ulong. Obviously, ulong is only 64 bits in size, and only the lowest 64
 bits of the "v" variable get set to 1, while the upper bits remain at 0.
 
 But there is something wrong. The compiler accepted this code, and it's
 silently wrong at runtime... I think the compiler should have rejected
 the integer literal.
 
 What do you think?
 
 Ap

The compiler should reject it, it rejects some literals (0x1_0000_0000_0000_0000) with the error "large_int.d(5) integer overflow". I think the reason it fail too is that it uses a very simplistic overflow detection algorithm (if it's smaller than before, it overflowed).
Jan 06 2008