Overflow-safe use of unsigned integral types
Jonathan M Davis
jmdavisProg at gmx.com
Sun Nov 10 13:26:17 PST 2013
On Sunday, November 10, 2013 21:40:14 rumbu wrote:
> On Sunday, 10 November 2013 at 12:19:18 UTC, mike james wrote:
> > When writing software for embedded micros you can always check
> > an overflow flag - is the no such mechanism on PC software?
>
> This is not overflow checking, it's the compiler considering a
> variable of type int implicitely convertible to equivalent
> unsigned types at bit level.
>
> I suppose it's a bug or may be the documentation is wrong
> (http://dlang.org/type.html):
>
> ubyte u1 = cast(byte)-1; // error, -1 cannot be represented in
> a ubyte
> ushort u2 = cast(short)-1; // error, -1 cannot be represented in
> a ushort
>
> These two lines are succesfully compiled by the last DMD on
> Windows.
Casts are never checked on integral types, so the documentation is outright
wrong in this case:
https://d.puremagic.com/issues/show_bug.cgi?id=11493
The only checks that are done with casts are
1. whether the compiler can convert from the original type to the requested
type (which has nothing to do with the values of anything - just the types)
2. whether a class instance is actually of the type beng cast to (and if it
isn't, the cast results in null)
When you cast, you're generally telling the compiler that you know what you're
doing and don't care what the compiler thinks about whether one value should
be converted to the other just so long as the types can do the conversion.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list