The `auto` keyword was repurposed in C++11 for a deduced type. When used to replace a type name in an initialized variable declaration, the variable is given the same type as the initializer. When used as a return type, the return type is specified as a trailing return type, or deduced from the return-expression.
Consider the following code:
bool Function()
{
return true;
}
bool result = Function();
The return type of Function
is unambiguously known at compile time, so the variable declaration can be replaced with:
auto result = Function();
The type of result
will thus be deduced. The auto
keyword becomes very useful, when type name is long:
for (std::vector<MyNamespace::MyType>::const_iterator iter = v.cbegin(); iter != v.cend(); iter++)
C++11 allows shorter declaration:
for (auto iter = v.cbegin(); iter != v.cend(); iter++)
It is worth noting that the keyword auto
changed meaning with advent of C++11 and it is almost always used in this new context.