What is the stance on partial initializers when declaring multiple variables of the same type?

Jonathan M Davis jmdavisProg at gmx.com
Sat Jul 23 02:41:41 PDT 2011


On Saturday 23 July 2011 07:16:07 Andrej Mitrovic wrote:
> On 7/22/11, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > Integral values wouldn't be 0 either if the
> > integral types had something akin to NaN.
> 
> Maybe if you're coming from C or C++ you're used to having to manually
> initialize everything.
> 
> I personally don't think the issue is about putting a variable in a
> known invalid state, but just about putting it in a known state to
> begin with. And you don't get either of those in C and C++.
> 
> I think 0 for integrals as a default is a great feature. It is a
> *known* feature, and it's pretty much what I want in 99% of my code. I
> only ever have to manually specify initializers in very few places for
> integrals, which saves me a lot of time.
> 
> Remember, D cares about usability as much as it cares about memory
> safety. 0 for integrals is a time-saving feature.

The values which were chosen for default initialization were specifically chose 
because they were the closest to an error value that each type has. In the 
case of integral values, there was no value which was really an error value, 
so 0 was chosen. Whether you rely on that or consider it good practice to 
always explicitly initialize variables is up to you. But it's was never really 
the point to avoid having to initialize variables. The point was to avoid 
undefined state and to make it as clear as possible what went wrong when you 
forgot to initialize a variable by making the default value as close to an 
error value as possible.

So, it's perfectly legitimate to rely on the fact that integral values default 
to 0 and not bother to ever initialize the directly, but avoiding having to 
directly initialize the variable wasn't really the reason for that language 
design decision.

Regardless, the fact that floating point values _can_ have an error value - NaN 
- means that you're never going to see 0 become the default value for floating 
point values even if most people typically initialized their floats to 0 (that 
and the fact that changing it at this point would break a lot of code).

- Jonathan M Davis


More information about the Digitalmars-d mailing list