Common type of ubyte and const ubyte is int
Steven Schveighoffer
schveiguy at gmail.com
Sun May 5 03:03:09 UTC 2024
On Friday, 3 May 2024 at 19:40:36 UTC, Walter Bright wrote:
> On 5/1/2024 7:42 AM, Steven Schveighoffer wrote:
>> It seems rule 2 would apply instead of rule 6? but I don't
>> like it.
>
> ```
> #include <stdio.h>
>
> void main()
> {
> char u;
> const char v;
> printf("%ld %ld\n", sizeof(u), sizeof(1?u:v));
> }
> ```
>
> This prints "1 4". D follows the same integral promotion rules,
> and the reason is if one translates C code to D, one doesn't
> get an unpleasant hidden surprise.
Cool, now let's try `char` against `char`:
```c
printf("%ld]\n", sizeof(1? u : u));
```
This prints 4 still. Wait, what does D do?
```d
ubyte u;
writeln((1 ? u : u).sizeof);
```
prints "1". This must be a mistake, right? How does anyone ever
port C code with this glaring change in functionality?!
I'm being a little bit overdramatic here, but you get the drift.
C does not have auto, or function overloading, so the inferred
type of a ternary expression in terms of *integer promotion* is
meaningless. There isn't even a *typeof* expression in C, so you
have to resort to `sizeof` expressions. As far as I can tell,
this is the only place where you can see the difference. Since C
allows implicit truncation, nobody will ever notice that this
type is `int`.
As pointed out by Daniel N, C++ gets this right. You know who
would be surprised by compiling C code if it did something *so
different* it affected outcomes? C++ developers. They use C
libraries as-is, not even porting, whenever they want. If those
things started misbehaving, they would notice.
But they don't care. Why? Because it doesn't affect anything in
C. Please, just change this.
-Steve
More information about the Digitalmars-d
mailing list