Docs: Section on local variables

Jonathan M Davis jmdavisProg at gmx.com
Fri Apr 20 11:40:36 PDT 2012


On Friday, April 20, 2012 03:22:43 Andrej Mitrovic wrote:
> Can we remove this section from the D docs, in the functions section? :
> 
> "
> Local Variables
> It is an error to use a local variable without first assigning it a
> value. The implementation may not always be able to detect these
> cases. Other language compilers sometimes issue a warning for this,
> but since it is always a bug, it should be an error.

There's no way that this is ever going to be the case. There are cases where 
you can't use a variable's initial value. For example,

T var;
if(cond)
{
 //do a bunch of stuff
 var = something;
}
else
 vare = somethingElse;

So, it can only really be initialized to a default value - which already 
happens automatically. And there's plenty of code out there that relies on the 
default values that variables are given and doesn't bother initializing them.

Personally, I think that variables should always be initialized rather than 
relying on the default value (even if you're initilazing them to the default 
value) except in cases where you're specifically deferring initialization and 
would use = void if you wanted the extra efficiency (though it's generally 
better not to use = void unless you need it, since there's definite risk 
associated with it). But there's no way that the compiler is going to enforce 
that, and if it did, it would require that you initialize the variable in the 
above example even though the compiler already does.

It seems to me that there are two approaches for the language to take:

1. Force all variables to be explicitly initialized, even if they don't really 
need to be (but the compiler can't always tell for sure). Java and C# take 
this approach.

2. Default-initialize everything. D does this.

The above doc excerpt is basically requiring #1 even though D already does #2. 
If that's the case, why have #2 at all? So, I'd vote to remove that from the 
docs. It isn't true, and I don't expect it to over be true.

> It is an error to declare a local variable that is never referred to.
> Dead variables, like anachronistic dead code, are just a source of
> confusion for maintenance programmers.
> "

This could done, but it's definitely _not_ a warning or error right now. It's 
also not ever going to be an error AFAIK, so I'd definitely vote to remove it 
from the docs. I know that Walter's already against making unused parameters 
either warnings or errors. It's a slightly different situation with local 
variables, since you don't have the overriding issue that can create unused 
variables with function parameters, but I also don't think that it's enough a 
problem to warrant an error. At most, it would be a warning, which wouldn't 
need to be mentioned in the docs IMHO. So, I definitely be for removing it as 
well.

- Jonathan M Davis


More information about the Digitalmars-d mailing list