The auto keyword

The auto keyword was changed in C++11 from being completely unnecessary to being a highly useful keyword.

Auto variable type (C++11)

The auto keyword tells the compiler to set the type of a variable to the type of the value that we assign to the variable. For example:

If you don’t assign a value to the variable, then the compiler will be lost and will refuse to compile since it cannot figure out the type to set;

auto can be really useful when some of the standard library operations where the type names can be really complex:

when creating a local lambda expression, then auto is a must:

Auto return type (C++14)

Beginning in C++14 can the return type of a function be auto:

Auto as lambda parameter (C++14)

From C++14 we can also use the auto keyword for the type of the parameters when writing a lambda expression. The lambda itself will then be a generic lambda, i.e. it will be compiled as a template:

will be compiled as:

 

Facebookgoogle_pluslinkedinmail