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.
If you'd read the IAQ (Infrequently Asked Questions) list, you'd know that auto is useful primarily to define or declare a vehicle:
auto my_car;
A vehicle that's consistently parked outdoors:
extern auto my_car;
For those who lack any sense of humor and want "just the facts Ma'am": the short answer is that there's never any reason to use auto
at all. The only time you're allowed to use auto
is with a variable that already has auto
storage class, so you're just specifying something that would happen anyway. Attempting to use auto
on any variable that doesn't have the auto
storage class already will result in the compiler rejecting your code. I suppose if you want to get technical, your implementation doesn't have to be a compiler (but it is) and it can theoretically continue to compile the code after issuing a diagnostic (but it won't).
Small addendum by kaz:
There is also:
static auto my_car;
which requires a diagnostic according to ISO C. This is correct, because it declares that the car is broken down. The diagnostic is free of charge, but turning off the dashboard light will cost you eighty dollars. (Twenty or less, if you purchase your own USB dongle for on-board diagnostics from eBay).
The aforementioned extern auto my_car
also requires a diagnostic, and for that reason it is never run through the compiler, other than by city staff tasked with parking enforcement.
If you see a lot of extern static auto ...
in any code base, you're in a bad neighborhood; look for a better job immediately, before the whole place turns to Rust.
Best Answer
It will break if your code contains the
auto
keyword. In nearly 30 years of C and C++ programming I've never come across any that did. The keyword was introduced in the first C compiler to specify local function variables, but compilers almost immediately became clever enough not to require it, and very little code that uses it will survive today - that's why C++0x chose to recycle it rather than introduce a new keyword which would cause portability problems.The purpose of the auto keyword in C++0X is to allow the compiler to work out the type of a variable, where this is possible:
the compiler can see that v.begin() must return a
vector<int>::iterator
and so can create a variable of that type, saving a lot of keyboarding or typedef creation.