Docs: Section on local variables

Jakob Ovrum jakobovrum at gmail.com
Fri Apr 20 02:39:17 PDT 2012


On Friday, 20 April 2012 at 01:22:53 UTC, 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.
>
> 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.
> "
>
> I don't think this will ever be implemented, or that it should 
> be for
> that matter. The first paragraph is quite extreme.

Many other languages have this restriction on local variables and
I would love to see DMD do the same kind of analysis. You can't
force programmers to write readable code, but you should at least
discourage it; the current way of default-initializing local
variables and using that as an excuse to not have flow analysis
is extremely weak and just reflects an unwillingness of the DMD
developers to take on this task, affecting the design of the
language.

I have seen this one in the wild before:

for(size_t i; i < arr.length; i++) {
      ...
}

This shouldn't be correct D code, and I think it's one of D's few
weaknesses that it is. Removing this paragraph from the
specification would be designing the language around DMD instead
of the other way around, and I really don't want to see that.

> As for the second one, think about how often you use temporary 
> variables just to test
> something out, you wouldn't want to have a compilation error 
> just
> because you've temporarily left an unused variable inside a 
> function.
> That's my experience anywho..

I think GDC has warnings for this, and I think that's the way to
go. Unused local variables is a plague on readability and we
should strive to eliminate them; but at the same time, a
compilation error for all circumstances may be a little tedious.

> I think these features probably belong to some lint-type tool 
> and not
> the compiler.

If I remember correctly, one of the goals of D according to
Walter is to reduce the need for such external tools.


More information about the Digitalmars-d mailing list