Showing posts with label auto. Show all posts
Showing posts with label auto. Show all posts

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.