[OT] The Usual Arithmetic Confusions
Guillaume Piolat
first.last at gmail.com
Fri Feb 4 15:00:18 UTC 2022
On Wednesday, 2 February 2022 at 23:27:05 UTC, Walter Bright
wrote:
> It also *causes* bugs. When code gets refactored, and the types
> change, those forced casts may not be doing what is desired,
> and can do things like unexpectedly truncating integer values.
>
> One of the (largely hidden because it works so well) advances D
> has over C is Value Range Propagation, where automatic
> conversions of integers to smaller integers is only done if no
> bits are lost.
+1
The cure would probably be worse than the "problem".
We should be careful what we wish for.
D does exactly what was so successful in C, integer promotion and
proper casts.
It cause zero surprise to a native programmer.
There is a difference.
C does the conversion to shorter integer implicitely, D does not
and if you translate you have to cast().
Yet, it isn't clear that the D code with the cast is less brittle
than the C code in that case, as when the type changes you get
neither a warning in C nor in D.
Example from qoi.d (translation of qoi.h)
----
byte vr = cast(byte)(px.rgba.r - px_prev.rgba.r);
byte vg = cast(byte)(px.rgba.g - px_prev.rgba.g);
byte vb = cast(byte)(px.rgba.b - px_prev.rgba.b);
----
When px.rgba.r changes its type, the D code will have no more
warning than the C code, arguably less.
Thus the top methods for detecting integer problems are in that
case:
1. No casts with VRP
2. ex aequo: D with cast, or C with implicit cast
It would be nice to "get over" the D integers, it's not like
there is a magic design that makes all problems go away, also as
of today people still translate from C to D all the time. It is
the state we are in today, where compatibility with C semantics
helps immensely.
More information about the Digitalmars-d
mailing list