What the heck am i doing wrong? I'm just trying to create a 8 bit unsigned variable.
H. S. Teoh
hsteoh at qfbox.info
Fri May 16 19:19:41 UTC 2025
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/mailman.282.1631547531.21945.digitalmars-d@puremagic.com
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
More information about the Digitalmars-d-learn
mailing list