One of the curious aspects of D when compared to C or C++ is that variables are default initialized according to their type when an assignment value isn't provided.
int foo() {
int o; // int.init == 0
o++;
return o; // returns 1
}
In contrast to C and C++, which simply leaves variables with potential garbage, D makes sure that garbage is never read from nearly all types of variables. However, considering this simple, merely hypothetical function, r
is never read before being set to i
, and it is certain that the assignment will happen eventually.
int foo2(int n) {
assert(n > 0 && n < 20);
int r;
for (int i = n ; ; i+=7) {
if (i % 3 == 0) {
r = i;
break;
}
}
return r;
}
This variable's initial value is not used. After initialization, the variable is either assigned another value or goes out of scope. Example: The following code excerpt assigns to the variable r and then overwrites the value without using it.
If T is scalar (arithmetic, pointer, enum), it is initialized from 0 ; if it's a class type, all base classes and data members are zero-initialized; if it's an array, each element is zero-initialized.
Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location!
- In a case where it is certain that a variable will be defined in the future without a previous read, will the default initialization still happen, according to the standard?
Since D doesn't have value-type constructors (default struct
constructors), initialization should not have any side effects, thus compilers are allowed to optimize it away. I believe this is a subset of dead assignment elimination.
- Is it known from the DMD/GDC compilers to optimize them out (as in, omitting default initialization when that default value is never read from the variable)?
The language specification does not impose a constraint on what optimizations an implementation must perform. The above example is non-trivial, so I would not be surprised if e.g. DMD would not optimize it away, or if GDC will on the maximum optimization level.
- If none of the above, is there a nice work-around to having a completely uninitialized variable?
Yes: int r = void;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With