Auto keyword and when to use it
Mike Parker
aldacron at gmail.com
Tue Aug 21 01:15:42 UTC 2018
On Monday, 20 August 2018 at 17:24:19 UTC, QueenSvetlana wrote:
>
> I'm struggling to understand what the auto keyword is for and
> it's appropriate uses. From research, it seems to share the
> same capabilities as the var keyword in C#.
auto is one of the most misunderstood understood features in D.
By that I mean, everyone understands the effect of auto, but
aren't always accurate in describing it.
In D, every variable must have a storage class. The automatic
storage class is the default and is never specified in the
declaration:
int x = 10;
Other storage classes are const, immutable, and shared. These are
also type constructors, so they become part of the type:
const int y = 11; // type is const(int)
immutable int z = 12; // type is immutable(int)
shared int s = 13; // type is shared(int)
D allows the type to be dropped in declarations that include an
initializer. In those cases, the type will be inferred:
const y = 11; // type is const(int)
immutable z = 12; // type is immutable(int)
shared s = 13; // type is shared(int)
You can also drop the type in declarations with automatic
storage, but `x = 10;` is not allowed as a variable declaration.
You must include at minimum a type or a storage class. That's
where auto comes in:
auto x = 10; // type is int
So that's all it is. It's nothing special. It just means you're
declaring a variable with the default storage class and want the
compiler to infer the type.
So the question 'when should I use auto' is probably the wrong
way to look at it. 'When should I use type inference' is a better
way to frame it. And the answer to that is that there is no right
answer.
I tend to use type inference liberally, almost always with
const/immutbale locals, though I tend to use auto only when the
type name is longer than four characters. For me, it's a nice way
to save keystrokes. Some take a dim view of that approach and
prefer to use it only when they actually require type inference.
I mostly program alone, though, and I have a number of habits
others may label 'bad', so I'm happy with my approach.
More information about the Digitalmars-d-learn
mailing list