The Auto Keyword


1.1.   Auto keyword

You can use the auto keyword as a type of a variable in a definition statement and have its type deduced from initial value you supply. Here are some examples
auto n = 16;                            // Type is int
auto pi = 3.14159;                  // Type is double
auto x = 3.5f;                         // Type is float
auto found = false;                 // Type is bool
In each case, the type assigned to the variable you are defining is the same as that of the literal used as the initializer. Of course, when you use the auto keyword in this way, you must supply an initial value for the variable. Variables defined using the auto keyword can also be specified as constants:
const auto e = 2.71828L; // Type is const long double
Of course, you can also use functional notation:
const auto dozen(12); // Type is const int
The initial value for a variable you define using the auto keyword can also be an expression:
auto factor(n*pi*pi); // Type is double
In this case, the definitions for the variables n and pi that are used in the initializing expression must precede this statement. 
Share on Google Plus