Auto keyword

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