float init 0 request

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Aug 14 08:09:45 UTC 2026


On Friday, August 14, 2026 1:05:06 AM Mountain Daylight Time Alexandru Ermicioi via Digitalmars-d wrote:
> On Friday, 14 August 2026 at 06:38:02 UTC, Walter Bright wrote:
> > Floats are default initialized to NaN so people will be coerced
> > to explicitly code what they want the initialized value to be.
> >
> > I've seen enough code where the programmer forgot to initialize
> > a float, it was defaulted to 0, and the wrong result was not
>
> Why not make it an error, a float that is not explicitly
> initialized? Would be way better than implicit nan
> initialization, right?

The language relies on the ability to default-initialize objects. For
instance, that's what happens when you allocate a dynamic array or increase
its length. There has to be a default value for that to work. It's part of
why adding the ability to disable default initialization for structs has
been a mess. It's arguably necessary for some contexts, but it means that
those structs can't legally be used in any context where default
initialization is required. Doing the same to floating point types would be
even worse given that they're a built-in type rather than something specific
to a particular code base.

Also, languages like Java where they make it illegal to use a variable
before you give it a value show how problematic it can be to make it an
error to not explicitly initialize a variable, because it's pretty easy to
get into situations where you know for sure that the variable is given a
value before it's used, but the compiler isn't smart enough to figure that
out, so you're forced to give it a dummy value just to shut it up.

D's approach of having all types have a default value is just cleaner and
simpler overall. It does kind of suck with regards to NaN, but the problems
with NaN largely exist because NaN exists at all, which goes way beyond the
issue of default initialization, and there's no getting around those issues,
because NaN is a standard part of IEEE floating point types.

- Jonathan M Davis






More information about the Digitalmars-d mailing list