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?

Limitations

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