Auto keyword and when to use it
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Aug 21 19:41:46 UTC 2018
On Tuesday, August 21, 2018 9:04:31 AM MDT Steven Schveighoffer via
Digitalmars-d-learn wrote:
> On 8/20/18 9:15 PM, Mike Parker wrote:
> > 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.
>
> I'm more extreme in this camp -- I use auto everywhere. Why? because at
> some point, I may change some type somewhere (oops, I should have wrote
> size_t instead of uint), and then I would have to go through and change
> all the places I put the concrete type if I hadn't used auto.
>
> While using functions, I also can use auto and not have to worry about
> the type. I know kind of what it is (integer type, string type, range
> type, etc), and not care what the exact type is.
I'd argue that it's generally better to use explicit types where possible in
function signatures so that the documentation is clearer, but overall, I
agree with you, and if I can use type inference, I almost always do.
However, it does seem like the sort of thing that many newcomers to D balk
at initially, whereas most of us who have been using it for a while have no
problem with it and prefer it.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list