Search⌘ K
AI Features

Using auto for Variables

Explore the effective use of the auto keyword in C++ to write safer and less cluttered code. Understand different forms of auto including const references, mutable references, and forwarding references. Learn best practices to optimize variable initialization, improve readability, and avoid common pitfalls while leveraging modern C++ standards.

Using the auto keyword for variable declarations

The introduction of the auto keyword in C++11 has initiated quite a debate among C++ programmers. Many people think it reduces readability, or even that it makes C++ similar to a dynamically typed language. We can (almost) always use auto as it makes the code safer and less littered with clutter.

Note: Overusing auto can make the code harder to understand. When reading code, we usually want to know which operations are supported by some object. A good IDE can provide us with this information, but it’s not explicitly there in the source code.

We can use auto for local variables using the left-to-right initialization style. This means keeping the variable on the left, followed by an equals sign, and then the type on the right side, like this:

C++ 17
auto i = 0;
auto x = Foo{};
auto y = create_object();
auto z = std::mutex{}; // OK since C++17

With guaranteed copy elision introduced in C++17, the ...