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.
Some major cases where auto
is helpful:
std::map<std::string, std::vector<int>>::iterator it;
// vs
auto it = myMap.begin();
std::function
In general, any time the type is lengthy or "obvious" from the context, auto
can avoid verbosity.
When using auto
:
int
and double