D arithmetic problem

bearophile bearophileHUGS at lycos.com
Thu Jun 4 01:22:10 PDT 2009


>* The use of -1 for "all bits set" is in widespread use and is important.<

I agree that it's common idiom in C code, but in a tidy language I may want to disallow the following:
uint x = -125;
because x can't represent -125, it's an error.
Likewise in D the following very common C idiom is an error ("cannot implicitly convert expression (0) of type int to int*") because they are of different type in D:
int *p = 0;
and you have to use null or nothing, because the variable is null by default.

In D instead of writing:
uint x1 = -1;
ushort x2 = -1;
ubyte x3 = -1;

You can write this, that is clear and safe:
uint x1 = uint.max;
ushort x2 = ushort.max;
ubyte x3 = ubyte.max;

But all that type duplication isn't nice, it's not DRY.
You can write the following that works correctly:
auto x1 = uint.max;
auto x2 = ushort.max;
auto x3 = ubyte.max;

But I don't like that much because it's fragile: if later you change the code a bit, for example like this:
auto x3 = ubyte.max + 100;
Now x3 is an int. Not good.

The following isn't a good solution because now you use the variable names three times, so it's not DRY still:
uint x1;
// x1 = typeof(x1).max; // not necessary, it seems
x1 = x1.max;
ushort x2;
x2 = x2.max;
ubyte x3;
x3 = x3.max;

Few possible alternative syntaxes, I like none of them:

uint.max x1;
ushort.max x2;
ubyte.max x3;

uint x1 = .max;
ushort x2 = .max;
ubyte x3 = .max;

uint x1 = x1.max;
ushort x2 = x2.max;
ubyte x3 = x3.max;

uint x1 = self.max;
ushort x2 = self.max;
ubyte x3 = self.max;

uint x1.max;
ushort x2.max;
ubyte x3.max;


Denis Koroskin:

>>* A lot of existing C code uses bitwise operations on ints.<<

>That's fine, raising an error in such cases is a good behavior.<

I tend to agree here.
(But from my coding experience I have seen that forcing the programmer to add lot of casts is bad. Because it's tedious, makes the code more noisy, and it's unsafe, because if you add 100 necessary casts, for mistake you may add 101 of them instead, and then the 101-st may produce a bug. So it's sometimes better to invent more refined/localized language rules, as other people have shown in this thread, instead of blunt ones that force to add too many casts to programs).


More information about the Digitalmars-d mailing list