Starting C++11, C++ contains a lot of improvements to the core language as well as a lot of additions to the standard library.
The aims for this new version, according to Bjarne Stroustrup were making C++ a better language for systems programming and library building, and making it easier to learn and teach.
auto is an already existing keyword inherited from C that was used to mark a variable as automatic (a variable that is automatically allocated and deallocated when it runs out of scope). All variables in C and C++ were auto by default, so this keyword was rarely used explicitly. The decision of recycling it and change its semantics in C++ was a very pragmatic decision to avoid incorporating (and thus, breaking old code) new keywords.
Since C++11, auto is used to infer the type of the variable that is being declared and initialized. For example:
int a = 8;
double pi = 3.141592654;
float x = 2.14f;
in C++11 and later, the code above can be declared in this way:
auto a = 8;
auto pi = 3.141592654;
auto x = 2.14f;
In the last example, the compiler will infer that a is an integer, pi is a double and x is a float.
Someone could say: “come on, I do not see any advantage on this because it is clearly obvious that ‘x‘ is a float and it is easy to me infer the type instead of letting the compiler to do that”, and yes, though the user will always be able to infer the type, doing it is not always as evident or easy as thought. For example, if someone wants to iterate in a std::vector in a template function, int the code below:
template <typename T>
void show(const vector<T>& vec)
{
for (auto i = vec.begin(); i != vec.end(); ++i) // notice the 'auto' here
std::cout << *i << std::endl;
}
the following declaration:
auto i = vec.begin();
in ‘old’ C++ would have to be written as:
typename vector::const_iterator i = vec.begin();
So, in this case, the auto keyword is very useful and makes the code even easier to read and more intuitive.
Anyway, there are restrictions on its usage:
- Before C++20, it is not possible to use
autoas a type of an argument of a function or method.
auto x = 2, b = true, c = "hello"; // invalid auto usage
Starting with C++14, the return type of functions can be deduced automatically (you can read more about that here). It can also be used in lambda expressions (more info here); . Starting with C++20, the arguments of a function can also be auto.
To read about auto see these links:
Excellent descriptions, short, concise + easy to understand examples!
Thanks for your comments and for reading me! :)