On Monday, 22 January 2024 at 06:43:17 UTC, thinkunix wrote:
Gavin Gray via Digitalmars-d-learn wrote:
The following code:

   ulong charlie = 11;
   long johnstone = std.algorithm.comparison.max(0, -charlie);
   writeln(format!"johnstone %s"(johnstone));

Results in (without any warning(s)):
johnstone -11

However you choose to look at it, this means -11 > 0 (regardless of all arguments concerning implicit conversions, 1's and 2's complements, being efficient, etc).

The language should not allow unary unsigned anything.


I have no idea what your use case is for this but...
WHY are you doing this??

If you declared charlie as unsigned, why would you then attempt to compare using a negative value? If you even had the possibility that charlie might be negative, why wouldn't you use a type that can accomodate the sign?

I'm sure they would if the compiler had stopped and provided an error message to tell them what they were doing. Note that in this line

```
long johnstone = std.algorithm.comparison.max(0, -charlie);
```

there is no direct assignment of a negative number to an unsigned type. The comparison is carried out as ulong and then there's an implicit conversion of a ulong to long, even though that can give a very weird result. It's perfectly natural to expect that everything will be carried out as a long since that's what's specified, or that a language like D will forbid implicit conversions if they can possibly give the wrong answer. If you change the long to int, the code will no longer compile.

Aside from the general statement that programmers make mistakes, D is prone to these issues because of the heavy use of auto, and because unsigned types are used for things like the length of an array.

Reply via email to