Search code examples
c++variablesauto

Surprisingly useful use of the keyword auto


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.


Solution

  • 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