Is `void` the correct way to say "do not initialize this variable"?

tsbockman thomas.bockman at gmail.com
Mon Oct 3 06:35:48 UTC 2022


On Sunday, 2 October 2022 at 23:45:45 UTC, drug007 wrote:
> It works but not as someone could expect. In case of
> ```D
> Foo[2] arr = void;
> ```
> `arr` value is not defined, it is not an initialized array of 
> uninitialized elements like you want, it is just uninitialized 
> array.

This is incorrect. It is not possible to declare an uninitialized 
static array variable in D; only the elements are affected by `= 
void`.

The meta data of a static array like `Foo[2] arr` (`.ptr` and 
`.length`) is determined statically at compile time and inserted 
where needed into the generated code. It is not stored in mutable 
memory the way a dynamic array/slice's meta data is, and does not 
need to be initialized at run time.

By contrast, it **is** possible to declare a completely 
uninitialized dynamic array, or to just leave its elements 
uninitialized:
```D
     // Meta data is not initialized, and no elements are 
allocated.
     // This has no static array equivalent:
     int[] arrA = void;

     // Meta data is initialized, and elements are allocated but 
not initialized.
     // This is the dynamic equivalent of the static:
     // int[2] arr = void;
     int[] arrB = uninitializedArray!(int[])(2);
```


More information about the Digitalmars-d-learn mailing list