2010-06-19 CPlusPlus0X

Auto is dead, long live auto

The keyword auto will get a new meaning. The old meaning is something you might not remember because in practice it was used very little. This was because it was the default so it could be left out and it normally was.

The new meaning is of more interest. Auto means that the type of a variable is deduced from its initializer expression. This can be as simple as

auto i = 1;

where the type of i will be int.

Of more practical use is when the initializer expression is more complex. Take for example the initialization of the loop variable in a for loop when traversing a standard library container. The loop variable takes the type of an iterator over the container. That was hard to write before but can now be written like this:

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