To init or not to init? (was: floating point verification using is?)

Stewart Gordon smjg_1998 at yahoo.com
Wed Dec 30 06:50:31 PST 2009


Don wrote:
<snip>
> I think we could get the behaviour you want by changing the definition 
> of T.init. I think it should ALWAYS be a bug to read an uninitialized 
> variable;
<snip>

All variables in D are initialized, unless overridden with a void 
initializer.  But what would "ALWAYS be a bug" mean?

(a) Trigger a compile-time error?

While some C(++) compilers will warn you if they catch you trying to 
read a variable before it's been set, they cannot be perfect at doing 
so.  That's probably one reason that D takes the simpler route.

(b) Trigger a run-time error?

This would be a performance hit, as you'd need
- extra working memory, as a bit to keep track of whether each variable 
is set
- extra code to set and check this bit when a variable is used
- extra CPU cycles to execute this extra code

I'd be inclined to save this kind of behaviour for scripting languages.

(c) Trigger undefined behaviour?

I can't see any real way of making it undefined short of going back to 
the C way.

One of D's reasons for initializing all variables is so that bugs caused 
by reading variables before they're otherwise set are easier to 
diagnose, since the behaviour doesn't change with every execution.

Another reason I can see is to avoid memory trample, possibly also GC 
horrors, caused by leaving pointers accidentally pointing somewhere and 
then trying to use them.  While you could get around this by defining 
that reference types are initialized to null and value types are not 
initialized, it's simpler to define that all variables are initialized.

A further complication is that, in a struct or class, some members may 
have default initializers set and others not.  Initializing a variable 
of struct or class type is much simpler if the fact of being initialized 
applies to the whole struct rather than some of its members.

(d) Be perfectly legal and defined, yet deemed immoral?

Stewart.


More information about the Digitalmars-d-learn mailing list