Look at it another way. Do you write:
std::cout << (foo() + bar()) << "\n";
or:
// it is important to know the types of these values
int f = foo();
size_t b = bar();
size_t total = f + b;
std::cout << total << "\n";
Sometimes it doesn't help to spell the type out explicitly.
The decision whether you need to mention the type isn't the same as the decision whether you want to split the code across multiple statements by defining intermediate variables. In C++03 the two were linked, you can think of auto
as a way to separate them.
Sometimes making the types explicit can be useful:
// seems legit
if (foo() < bar()) { ... }
vs.
// ah, there's something tricky going on here, a mixed comparison
if ((unsigned int)foo() < bar()) { ... }
In cases where you declare a variable, using auto
lets the type go unspoken just as it is in many expressions. You should probably try to decide for yourself when that helps readability and when it hinders.
You can argue that mixing signed and unsigned types is a mistake to begin with (indeed, some argue further that one should not use unsigned types at all). The reason it's arguably a mistake is that it makes the types of the operands vitally important because of the different behaviour. If it's a bad thing to need to know the types of your values, then it probably isn't also a bad thing not to need to know them. So provided the code isn't already confusing for other reasons, that makes auto
OK, right? ;-)
Particularly when writing generic code there are cases where the actual type of a variable shouldn't be important, what matters is that it satisfies the required interface. So auto
provides a level of abstraction where you ignore the type (but of course the compiler doesn't, it knows). Working at a suitable level of abstraction can help readability quite a lot, working at the "wrong" level makes reading the code a slog.
auto
can often makes things harder to read when they are already hard to read, i.e., functions too long, variables poorly named, etc. On short functions with decently named variables, knowing the types should be one of #1 easy or #2 irrelevant.auto
is a lot like determining when to usetypedef
. It's up to you to determine when it hinders and when it helps.auto x = GetX();
, pick a better name thanx
that actually tells you what it does in that specific context ... that's often more useful than its type anyway.