auto
Declarations in C++11
C++11 introduces a facility that allows the compiler to deduce a type from the type of an initialization value. For this purpose it redefines the meaning of auto
, a keyword dating back to C, but one hardly ever used. (Chapter 9 discusses the previous meaning of auto
.) Just use auto
instead of the type name in an initializing declaration, and the compiler assigns the variable the same type as that of the initializer:
auto n = 100; // n is intauto x = 1.5; // x is doubleauto y = 1.3e12L; // y is long double
However, this automatic type deduction isn’t really intended for such simple cases. Indeed, you might even go astray. For example, suppose x
, y
, and z
are all intended to be type double
. Consider the following ...
Get C++ Primer Plus 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.