Static struct initialization syntax behavior & it being disabled upon adding a constructor

user1234 user1234 at 12.de
Mon Apr 18 13:02:06 UTC 2022


On Monday, 18 April 2022 at 10:26:16 UTC, HuskyNator wrote:
> On a sidenote, I'm surprised D did not choose 0 as the default 
> floating value. Doesn't almost every language do this? I 
> understand the thinking behind it, but when the type one uses 
> in a template influences the behavior of the code, that seems 
> like a pretty big red flag to me. (Any non-floating type 
> defaults to 0, but using floats/doubles suddenly introduces 
> NaN, surely I'm not the only one that sees a problem with this 
> 😅) Especially when it's basically a standard 0 is used for 
> this. Sorry for the rant.

Let me explain the why:

D default initialization is not designed to replace user-defined 
initialization, it's rather made to make bugs related to 
non-initialized variables stable, e.g not UB.

The easiest way to get that is to think to references and 
pointers. A random garbage value pointed by an alloca may work to 
some point (e.g access to member), if it's set to `null` right 
after the alloca then you have a stable segfault that always 
happens at the same time and is easy to debug.

Similarly, for floating point numbers the D designers considered 
that `NaN` was the best choice because FP operations will not 
wrongly appear valid when starting operations with NaN.

With integral types, this system does not work as well, as `0` 
doesn't create bugs as easily as `null` and `NaN`. The confusion 
about the real role of default initialization comes from integral 
types I believe.


More information about the Digitalmars-d-learn mailing list