Best of 2012: auto

Perhaps the most common single question about C++11 is: When should we use auto to declare local variables?

Here's a current set of responses on Programmers.StackExchange. Enjoy.

Does auto make C++ code harder to understand?

I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand -- every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

auto x = GetX();

Than:

 

someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder -- does auto make C++ code harder to understand?

Continue reading...

Add a Comment

Comments are closed.

Comments (2)

0 0

Zenju said on Dec 27, 2012 10:44 AM:

Using "auto" everywhere possible is like using the word "stuff" in every sentence instead of the proper term. Sure one can deduce what was meant, but readability suffers because "something" is meaningless without context. Redundancy facilitates understanding, especially for humans.
0 0

Cedric said on Dec 28, 2012 03:28 AM:

agreed. Such rules as "use auto everywhere possible" just sounds too general.