3

I am more than a little surprised by this fascinating discovery, and I am wondering how "safe" it is to rely on it.

The auto keyword has historically rarely been used since it is implicitly implied anyway:

{ auto int x=5; }

Is the same as:

{ int x=5; }

So then I was poking my way around Stackoverflow, which is a great site that I highly recommend. And I discovered this fascinating nugget: In the new c++ you can use auto to infer type.

This sure does reduce a lot of typing. For example, instead of this, which I am working on right now:

 std::chrono::high_resolution_clock::time_point 
     t1 = std::chrono::high_resolution_clock::now();

I can just do this instead:

 auto t2(std::chrono::high_resolution_clock::now());

So what I'd like to know is.... how good of a habit am I building by doing this fairly often?

The "auto" tag here on Stackoverflow says this keyword works when it can be "unambiguously deduced" what the type is. That implies to me that it is quite safe and a fine habit, so long as you don't plan to support compilers of older generations of the language.

Community
  • 1
  • 1
johnbakers
  • 24,158
  • 24
  • 130
  • 258
  • 3
    As [someone](http://stackoverflow.com/questions/15737223/when-should-i-use-c1y-automatic-return-type-deduction#comment22361511_15737723) so nicely put it for return type deduction (it works here as well): *Is it better for your code to say, "the type of this thing is X", or is it better for your code to say, "the type of this thing is irrelevant, the compiler needs to know and we could probably work it out but we don't need to say it"* – chris Apr 06 '13 at 05:03
  • 1
    Concur with chris. Use `auto` where *appropriate*. Don't abuse it. Your code just becomes that much harder to read. – WhozCraig Apr 06 '13 at 05:09

1 Answers1

3

You can learn from Google who has shared its wisdom about the preferred use of 'auto' with the rest of us:

Use auto to avoid type names that are just clutter. Continue to use manifest type declarations when it helps readability, and never use auto for anything but local variables.

Read more at http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#auto

dragonroot
  • 5,653
  • 3
  • 38
  • 63
  • Caveat about Google's C++ style guide: A lot of experienced C++ programmers on Stack Overflow disagree with many points in that guide. Nevertheless, that particular tidbit about `auto` is sensible. – In silico Apr 06 '13 at 05:14
  • Thats a good summary. Avoidance where it *hinders* readability is spot-on, and honestly my main bitch about people that abuse it. – WhozCraig Apr 06 '13 at 05:15
  • Thank you all, good points many. – johnbakers Apr 06 '13 at 05:25