Are redundant initializations ruled out by default?

One of the curious aspects of D compared to C or C ++ is that the default variables are initialized according to their type when no assignment value is provided.

int foo() { int o; // int.init == 0 o++; return o; // returns 1 } 

Unlike C and C ++, which simply leaves variables with potential garbage, D ensures that garbage is never read from almost all types of variables. However, given this simple, simply hypothetical function, r never read until the value i , and it is certain that the assignment will finally happen.

 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; } 
  • In the case when I am sure that the variable will be defined in the future without a previous reading, will the default initialization still happen, according to the standard?
  • Is it known from DMD / GDC compilers to optimize them (as in omitting the default initialization, when this default value is never read from a variable)?
  • If none of the above is there, is there a good job with a completely uninitialized variable?
+7
initialization d
source share
1 answer
  • In the case when a certain variable will be defined in the future without a previous reading, will the default initialization be performed in accordance with the standard?

Since D does not have value type constructors (default constructors are struct ), initialization should not have any side effects, so compilers are allowed to optimize it. I believe this is a subset of the elimination of dead appointments.

  1. Is it known from DMD / GDC compilers to optimize them (as, for example, in the absence of default initialization, when this default value is never read from a variable)?

The language specification does not impose restrictions on which optimizations an implementation should perform. The above example is non-trivial, so I would not be surprised if, for example, the DMD does not optimize it, or if the GDC is at the maximum level of optimization.

  1. If none of the above is there, is there a good job in order to have a completely uninitialized variable?

Yes: int r = void;

+7
source share

All Articles