Implicit type conversions with data loss
bearophile
bearophileHUGS at lycos.com
Tue Jun 5 15:17:56 PDT 2012
ctrl:
> I don't want them to be performed at all. How do I disable this
> 'feature'?
>
> For example, take a look at this code:
>
> import std.stdio;
> void main() {
> int x = -1;
> uint b = x;
> writeln(b);
> }
>
> It outputs 4294967295, but I want a compile-time error instead.
> Any suggestions?
> (compiler version dmd 2.059)
D is designed to be a safe language, maybe it will be used for
industrial processes that require a significant amount of safety.
So D tries to _statically_ refuse value conversions that cause
data loss. But for practical reasons (this mean to avoid the
introduction of too many casts, that are even more dangerous)
this rule is not adopted in some cases. As example D allows you
to assign doubles<==float, that causes some precision loss.
An int and uint are represented with 32 bits, so casting one to
the other doesn't cause data loss, but the range of the numbers
they represent is different, so in general their conversion is
unsafe.
Languages as Ada, Delphi, C# and few others (C/C++ too, with a
new Clang feature) know that overflow of fixnums is a very common
source of bad bugs, so they offer optional run-time tests to
assignments and numerical operations. D too will eventually need
those.
In the meantime you can do this, that's not so fast (the inlined
tests in Ada/C#/Delphi are far faster):
import std.stdio, std.conv;
void main() {
int x = -1;
auto b = to!uint(x);
writeln(b);
}
Or you can add an assert/enforce, or you can create a small
struct that represent safely assignable uints, etc. No solution
is good.
Bye,
bearophile
More information about the Digitalmars-d
mailing list