Why is char initialized to 0xFF ?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Jun 9 13:45:07 UTC 2019


On Sunday, June 9, 2019 3:27:39 AM MDT KnightMare via Digitalmars-d wrote:
> On Sunday, 9 June 2019 at 08:36:30 UTC, Patrick Schluter wrote:
>
> I read the bible too. I know reasons why leaders decided use NaN
> and FF.
> but
> what is the best solution:
> do some math and get garbage in C++ or NaN in D?
> or compiler will tell "using unitialized variable" before any
> math?

Given how init works in D and how it's used all over the place, it really
isn't feasible to have the compiler tell you to initialize the variable. A
prime example would be with dynamic arrays. Mutating the length of a dynamic
array has to use the init value. e.g.

arr.length += 15;

wouldn't work if init weren't used. Another example would be out parameters.
They get assigned the init value for the type when the function is called.

A lot of aspects of D are built around the fact that every type has an init
value and the fact that values of that type are always initialized to that
init value if they're not given an explicit value. At some point during the
language's development, the ability to @disable the default intialization of
a type was added, but even those types still have an init value. And while
it works, @disabling default initialization causes all kinds of subtle
problems precisely because D was built around the idea that every type could
be default-initialized.

Sure, there are some downsides to D's approach (such as getting unexpected
NaNs or not having default constructors for structs), but it also solves a
whole class of problems that other languages like C and C++ have with
garbage values. Even Java has problems with garbage values in spite of it
requiring that you initialize variables before using them (e.g. it's quite
possible to use a static variable in Java before it's initialized because of
circular reference issues). D, on the other hand, never has garbage values
unless you use @system features like = void to force it.

- Jonathan M Davis





More information about the Digitalmars-d mailing list