Variables, Types and Operators

When should I use auto in C++?

The auto keyword seems convenient, but the lesson says to use it sparingly. When is it appropriate to use auto in C++?

Abstract art representing computer programming

The auto keyword in C++ is used for type deduction. When you use auto, the compiler infers the type of the variable from its initializer. This can be convenient and can make your code more readable in certain situations:

Example 1: When the type is long or complicated, especially when using templates:

std::map<std::string,
  std::vector<int>> my_map{GetMap()};
// vs
auto my_map{GetMap()};

Example 2: When the exact type isn't important for understanding the code:

// If we only care that result is,
// say, a number, auto is fine
auto result = some_complex_function();

Example 3: With iterators, where the exact type can be verbose:

for (std::vector<int>::const_iterator it =
  vec.begin(); it != vec.end(); ++it) {
  // ...
}

// vs

for (auto it = vec.begin();
  it != vec.end(); ++it) {
  // ...
}

However, there are also situations where using auto can make your code less readable or even cause bugs:

Example 1: When the type is not immediately clear from the context:

// Is this an int? A long?
// Unclear without more context.
auto x = 5;

Example 2: When you need to be explicit about type conversions:

// The cast is hidden
auto result = static_cast<int>(some_float);

Example 3: When you want to commit to a specific type:

// i is an int
auto i = 5;

// j is a long, which might not be what you want
auto j = 5L;

As a rule of thumb, use auto when it makes your code more readable by avoiding long type names or when the exact type isn't important. But prefer explicit types when the type is not immediately clear, when type conversions are involved, or when you want to commit to a specific type.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved