More Uses for auto
auto by showing some more contexts in which it makes programs easier to read.
This post continues last week's discussion of auto by showing some more contexts in which it makes programs easier to read.
There are many contexts in which we write expressions without caring about the details of those expressions' types, typically because we use them as parts of other expressions. For example, if a, b, and c are the coefficients of a quadratic equation, the equation's roots are
(-b + sqrt(b * b – 4 * a * c)) / (2 * a)
and
(-b - sqrt(b * b – 4 * a * c)) / (2 * a)
Suppose we want to print those roots. We might write something like this:
cout << "Roots: " << (-b + sqrt(b * b – 4 * a * c)) / (2 * a)
<< " and " << (-b - sqrt(b * b – 4 * a * c)) / (2 * a) << endl;
However, doing so clearly repeats a lot of code. We can use auto to make it easier to factor this code:
auto d = sqrt(b * b – 4 * a * c), e = 2 * a; cout << "Roots: " << (-b + d) / e << " and " << (-b – d) / e << endl;
I can think of no reason for a programmer who wants to refactor code in this way to have to figure out what types to give d and e. In fact, I think that it is less clear to define d and e this way:
double d = sqrt(b * b – 4 * a * c), e = 2 * a;
because now the reader must figure out whether the types of d and e were declared correctly, or whether sqrt(b * b – 4 * a * c) yields a type, such as long double, that will lose information on being converted to double.
We can find another example of using auto to simplify code by looking at make_pair. If a has type A and b has type B, then make_pair(a, b) is an object of type pair<A, B>. So, for example, we can write
pair<int, double> p = make_pair(3, 4.5);
after which p.first is 3 and p.second is 4.5.
I claim that restating the type pair<int, double> makes this code harder to read, not easier. Moreover, making the expressions more complicated increases the benefit of auto. Why write
pair<pair<int, double>, pair<double<int>>> p =
make_pair(make_pair(3, 4.5), make_pair(6, 7.8));
when you can write
auto p1 = make_pair(3, 4.5),
p2 = make_pair(6, 7.8);
auto p = make_pair(p1, p2);
In short, I believe that auto is like so many programming tools: It can make programs easier or harder to read depending on how you use it.

