THE AUTO KEYWORD

You can use the auto keyword as the type of a variable in a definition statement and have its type deduced from the 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 of these cases, 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.

When you use auto, you are telling the compiler to figure out the type of the variable. The auto keyword may seem at this point to be a somewhat trivial feature of C++, but you’ll see later in the book, especially in Chapter 10, that it can save a lot of effort in determining complicated variable types and make your code more elegant.

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.