...

/

Using auto for Variables

Using auto for Variables

Learn how to use the auto keyword when declaring variables.

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:

Press + to interact
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 ...