Auto keyword
...

Using auto allows you to omit the explicit type when declaring a variable. The compiler will deduce the type based on the initializer expression:

auto x = 5; // x is int
auto y = 3.14; // y is double

This avoids having to spell out the type yourself and lets it be determined automatically.

Key Use Cases:
...

Some major cases where auto is helpful:

  • Declaring iterators or other long, complex STL types:
std::map<std::string, std::vector<int>>::iterator it;
// vs
auto it = myMap.begin();
  • Generic programming with templates
  • Lambda expressions and std::function
  • Initializing variables with constructors

In general, any time the type is lengthy or "obvious" from the context, auto can avoid verbosity.

Pros:
...

  • Avoids repetitive declarations
  • Makes code more maintainable
  • Allows flexibility for type changes
  • Omits verbosity like complex STL types

Cons:
...

  • Can reduce code readability since type not visible
  • Requires C++11 or higher
  • Auto type not explicitly stated

Best Practices:
...

When using auto:

  • Only use when type is obvious from initializer
  • Avoid for multiple declarators in one statement
  • Avoid for numeric types like int and double