Ch2.10: auto
What is auto?
The keyword auto tells the compiler to deduce the type of an object from its initializer.
Instead of writing the type explicitly, you let the compiler figure it out.
Basic Examples
#include <cstddef>
auto a{42zu}; // deduced as ::std::size_t
auto b{3.14}; // deduced as double
auto c{'x'}; // deduced as char
auto d{true}; // deduced as bool
Each object is initialized with a literal, and the compiler deduces the correct type automatically.
Why Use auto?
- Reduces repetition when the type is obvious from the initializer.
- Improves readability when types are long or complex.
- Helps avoid mistakes when working with template-heavy code.
Limitations
autorequires an initializer — you cannot declareauto x;without one.- The deduced type may not always be what you expect (e.g., narrowing conversions).
- Be cautious:
autodeduces by value unless you explicitly add&orconst&.
References with auto
#include <cstddef>
::std::size_t x{100zu};
auto r1{x}; // deduced as ::std::size_t (copy)
auto& r2{x}; // deduced as ::std::size_t& (reference)
auto const& r3{x}; // deduced as ::std::size_t const& (const reference)
Adding & or const& changes the deduction to a reference type.
Key Takeaways
autodeduces the type of an object from its initializer.- Always provide an initializer when using
auto. - Use
&orconst&withautoto bind references. - Improves readability and reduces repetition, especially with complex types.