I will don my asbestos suit and offer a somewhat contrary opinion.
I use
auto
on almost every possible occasion. Why? It keeps the code tight rather than spilling lines when a long type name would otherwise have to replace
auto
. But that's only the first reason.
Not using
auto
in order to make the code easier to understand can easily lend a false sense of security. Why is someone looking at my function's implementation? If it's because my interface didn't document it well enough,
that is what needs to be fixed. But if the interface is OK, they're looking at the implementation because there are details that they need to understand. Maybe they think there's a bug, in which case they might even need to fix it.
So if they see
auto
and don't know what type it represents, it means they don't understand the right-hand side of the expression that is imputing its type to the left-hand side. Quite often, the right-hand side is a function call. In which case it means they don't understand what that function does, so they'd better investigate if they want to truly understand what's going on. It doesn't really help to tell them what the type is, because they need to look at that function's documentation and maybe even its implementation.
Just be sure you know what type
auto
will assign. One of the few places I specify the actual type is in this kind of loop:
for(size_t i = 0; i < vec.size(); ++i)...
Here, if you use
auto
for
i
, you get an
int
(the default type for
0
). But
size()
returns
size_t
. That's an
unsigned int
, so you have to specify
size_t
explicitly.