What is the correct use of auto?

Steven Schveighoffer schveiguy at yahoo.com
Fri Apr 11 06:49:44 PDT 2008


"Hans W. Uhlig" wrote
>I have been reading through the specification and playing with D more and 
>more, what is the purpose of auto. I can understand in languages with 
>scalar types handling datatypes on assignment but on a strictly typed 
>language like C or D when would auto(as a variable declaration) provide 
>more useful functionality then it removes from readability.
>
> When would this be useful rather then simply specifying the type?

The best reason for auto is maintainability.

If you decide to change what some function returns, then you have to go 
through all your code and change the return type in all places it is used. 
If you use auto, it's already done :)  Most frequent thing that happens to 
me is, I find I've declared something as returning int, and realize it 
really should have been uint.

The second best reason is for template instantiation:

TemplateClass!(int, string, 5) variable = new TemplateClass!(int, string, 
5);
vs.
auto variable = new TemplateClass!(int, string, 5);
There's also a maintainability aspect to that as well, if you decide to 
change the template type.

I've spottily used auto, and I've found in many cases that I wished I had 
used it everywhere :)  seldom does it hurt you to use it, and it's usually 
pretty clear what it means.

-Steve 





More information about the Digitalmars-d mailing list