January 07, 2008 excessively long integer literal | ||||
---|---|---|---|---|
| ||||
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 |
January 07, 2008 Re: excessively long integer literal | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ap Lee | 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).
|
Copyright © 1999-2021 by the D Language Foundation