Friday, December 14, 2012

auto overused

I had recently read on an article on a programming subject not related to C++11 but which uses C++11 constructs to explain the point. It is nice to see that C++11 is being adopted this way. However one thing that scared me was the overuse of auto keyword.

const auto MAXSIZE = 10000;

for (auto i = 0; i < MAXSIZE; ++i)
{
...
}

This chills me to the bone. Why not use int or size_t? Of course this simple code doesn't show the complete threat that is the overuse of auto. But this introduces a culture where is OK to use auto everywhere.

My feeling about auto is that it is a tool best fitted for generic programming or where writing the type is difficult, complicated or impossible. Compare this:
std::vector<int> v;

for (std::vector<int>::const_iterator it = v.begin(); it = v.end(); ++v)
{}

with the better:

std::vector<int> v;

for (auto it = v.begin(); it != v.end(); ++v)
{}

but this is even better and clearer:
std::vector<int> v;

for (int &i : v)
{}


Excessive use of auto can lead code that is hard to read and to maintain. Maintenance is all about code reading. Please take care.

1 comment:

lanzkron said...

It's a shame that both your options for replacing the old for loop have different semantics than the original.

In the first example you should use cbegin so as to get a const_iterator rather than a regular iterator, in the range-based-for loop you explicitly seem to be going for a mutable int, why do you need the reference? If it weren't an int you could have used const auto&.

There are actually places in which auto can be harmful, when they interact with expression templates. See my blog post from 2011.

http://lanzkron.wordpress.com/2011/02/21/inferring-too-much/