To init or not to init?

Don nospam at nospam.com
Wed Dec 30 09:01:07 PST 2009


Stewart Gordon wrote:
> 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.
> 

Yes, but it can be a QOI issue. That is, it's always a bug, the compiler 
will do the best it can to detect it at compile time, but it isn't 
always possible. Proof:

bool arbitrarily_difficult() {}
int main()
{
   int x;
   if (arbitrarily_difficult()) x=7;
   return x;
}

So it's clearly an NP-hard problem.

So we have run-time initialisation to catch the cases that are too hard 
for the compiler.


> (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?

The question is, are they initialized solely in order to help detect 
bugs, or are they initialized so that you can use them?





More information about the Digitalmars-d-learn mailing list