Variable declaration programming style and the auto keyword

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 4 13:15:06 PDT 2013


On Thursday, July 04, 2013 21:54:22 Jeremy DeHaan wrote:
> I've seen a lot of code lately that uses the auto keyword when
> declaring variables, but for some reason I don't really care much
> for it.
> 
> I'd like to make tutorials for a library I am working on, but I
> want to use "D style." Does such a style exist? Is auto generally
> preferred when declaring variables?
> 
> How often does everyone here use it?

There's some debate as to how much to use auto, but at absolute minimum, it 
should be used it situations where

1. Using it would just unnecessarily duplicate the type, like in

int i = cast(int)foo;
MyClass c = new MyClass;
int[] arr = new int[](5);

Those definitely should be

auto i = cast(int)foo;
auto c= new MyClass;
auto arr = new int[](5);


2. Where giving the exact type would be tedious. For instance, with 
std.algorithm.until. You could write

Until!("a == b", int[], int) result = [1, 2, 3, 4, 5].until(3);

or you could write

auto result = [1, 2, 3, 4, 5].until(3);


3. When you need to infer the type. This is frequently the case in generic 
programming, as the type could change depending on what was passed to a 
templated function, and with Voldemort types (return types which are declared 
internally to a function, so you don't have access to their name), you _have_ 
to use auto. This is frequently done with range-based algorithms, as the type 
doesn't matter, just the API.


So, at _absolute minimum, auto should be used in those circumances. However, 
many of us would argue that auto should almost always be used unless you 
actually need to give an explicit type. And a _lot_ of D code is written this 
way. By using auto heavily, refactoring code becomes _much_ easier, because 
you don't have to go and change the type of your variables all over the place 
when you make changes.

If you need the type to be explicit, then you have to make it explicit. For 
instance,

auto i = 7;

will result in i being an int when maybe you need to be be size_t. In such 
cases, you'd have to explicitly give the type.

size_t i = 7;

And of course, there are times when using an explicit type improves clarity, 
so there's some art to choosing when to use auto and when not to, but for the 
most part, code is more maintainable when you don't use explicit types when 
you don't actually need to.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list