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

tsbockman thomas.bockman at gmail.com
Mon Oct 3 06:54:49 UTC 2022


On Sunday, 2 October 2022 at 23:30:16 UTC, ryuukk_ wrote:
> ```D
> MyStruct test = void;
> ```
>
> Does this guarantee that the compiler will not initialize it?

It's more of a request, than a guarantee. For example, `= void` 
may be ignored for the fields of `struct`s and `class`es:
```D
struct ABC {
     char a = 'a';
     char b = void;
     char c = 'c';
}

void main() @safe {
     import core.lifetime : emplace;
     import std.stdio : write, writeln;

     ABC abc = { a: 'x', b: 'y', c: 'z' };
     emplace(&abc);
     write(`a: '`, abc.a, `', b: '`);
     if(abc.b != 0)
         write(abc.b);
     else
         write(`\0`);
     writeln(`', c: '`, abc.c, `'`);
}
```

If the `= void` actually prevented initialization of `b`, the 
above would print:
```
a: 'a', b: 'y', c: 'c'
```
However, it actually prints this instead on all D compilers with 
which I tested:
```
a: 'a', b: '\0', c: 'c'
```
This is because it is considered needlessly complicated - and, at 
least for smallish types, possibly actually slower - to support 
uninitialized gaps when blitting `.init` values.

> Does it work with static arrays of struct too?

Yes.


More information about the Digitalmars-d-learn mailing list