Can we just have struct inheritence already?

Timon Gehr timon.gehr at gmx.ch
Sat Jun 15 13:39:13 UTC 2019


On 15.06.19 10:40, XavierAP wrote:
>>>
>>
>> Yes. And the bug is either
>> - that `void` initialization of `bool` is `@safe`.
>> - that `void` initialization of `bool` can produce a value that is 
>> both `true` and `false`.
>> - that boolean values are assumed to be either `true` or `false` in 
>> @safe code.
> 
> I'm not yet sure in the general case about void initialization, but for 
> me this interesting case shows that:
> 
> - void initialization of bool should be illegal, not just in @safe code, 
> anywhere. Initializing an int void works as (undefinedly) as intended, 

Accessing a `void`-initialized `int` may work with current compilers, 
but this is not guaranteed by the spec.

> but with bool it breaks the spec;
> ...

It does not break the spec:

"Undefined Behavior: If a void initialized variable's value is used 
before it is set, the behavior is undefined."

https://dlang.org/spec/declaration.html#void_init

Undefined means the behavior can be anything at all, including that the 
program behaves as if some bool was true and false at the same time. As 
soon as you trigger undefined behavior, you can't assume that the 
program that is executing is actually the program that you wrote.

> - I never understood why D adopted over from C/C++ that bool is int and 
> implicitly convertible; I don't understand when this may be useful.

It can be useful, but it is not necessarily worth the savings (because 
(b?1:0) is so short).

One case where I sometimes use it is if I need four offsets to 
neighboring grid squares, then I just write:

int i,j; // position of current grid square
foreach(k;0..4){
     auto ni=i+(k==0)-(k==1);
     auto nj=j+(k==2)-(k==3);
     foo(ni,nj); // do something with neighbor
}

Without the feature, I could write

int i,j;
foreach(k;0..4){
     auto ni=i+(k==0?1:k==1?-1:0);
     auto nj=j+(k==2?1:k==3?-1:0);
     foo(ni,nj);
}

Another case where it may be useful is if you like to initialize your 
bools using literals `0` and `1`.


More information about the Digitalmars-d mailing list