On Fri, May 16, 2025 at 07:04:24PM +0000, WhatMeWorry via Digitalmars-d-learn
wrote:
[...]
> void main()
> {
> ubyte a;
> a = a + 5; // onlineapp.d(11): Error: cannot implicitly convert
> expression `cast(int)a + 5` of type `int` to `ubyte`
[...]
Welcome to your first encounter with why I hate D's narrow integer
promotion rules.
Basically, `a + 5` gets promoted to int, and that's why it can't be
assigned back to `a`. (Don't ask me why, that's just the way it is and
Walter has refused and probably will continue to refuse to change it.)
Ironically, this is OK:
```
ubyte a;
a += 5;
```
But writing it as `a = a + 5;` is not.
You can't just decide to use the `<op>=` form to work around this every
time either. For example, how do you negate a ubyte? Obviously, you
can't do this:
```
ubyte a;
a -=;
```
But writing it as `a = -a;` runs into the same error, for the same
reason.
Instead, you have to work around it with this baroque periphrasis:
```
ubyte a;
a = cast(ubyte) -a;
```
Does it make sense?
Yes, it's just a consequence of integer promotion rules.
Does it make sense?
Intuitively, absolutely not.
What's the solution? Maybe this might interest you:
https://forum.dlang.org/post/[email protected]
T
--
Claiming that your operating system is the best in the world because more
people use it is like saying McDonalds makes the best food in the world. --
Carl B. Constantine