Just a friendly reminder about using arrays in boolean conditions

Steven Schveighoffer schveiguy at gmail.com
Sun Nov 17 22:17:18 UTC 2024


On Sunday, 17 November 2024 at 21:50:18 UTC, kdevel wrote:
> My question is: Is it possible that a valid D program gets into 
> a
> state where an array has ptr == null and length > 0? If so, how?

Yes, the compiler uses it:

```d
struct S
{
     int x;
}

void main()
{
     auto i = typeid(S).initializer;
     assert(i.ptr is null);
     assert(i.length > 0);
}
```

For a type that is all 0, the compiler builds `initializer` to be 
a null array with a length. This signifies to the runtime that 
the type is all 0 initializer, but has a specific length. This 
allows saving binary space by not storing a bunch of 0s.

-Steve


More information about the Digitalmars-d mailing list