Is there any reason to use the ‘auto’ keyword in C++03?

In C++11, auto has new meaning: it allows you to automatically deduce the type of a variable.

Why is that ever useful? Let’s consider a basic example:

std::list<int> a;
// fill in a
for (auto it = a.begin(); it != a.end(); ++it) {
  // Do stuff here
}

The auto there creates an iterator of type std::list<int>::iterator.

This can make some seriously complex code much easier to read.

Another example:

int x, y;
auto f = [&]{ x += y; };
f();
f();

There, the auto deduced the type required to store a lambda expression in a variable.
Wikipedia has good coverage on the subject.

Leave a Comment