auto
is a C++ feature that arrived in the dawn of C++ 11.
It does mostly 2 things for you:
- Shorter syntax. Who doesn't like writing shorter types, right? Although sometimes it's not practical, and it's really up to the person to decide. So for example, this:
std::vector<unsigned int>::size_type i = 0;
...gets reduced to:
auto i = 0;
And that's what I was talking about, regarding practicality. Sometimes, there are lots of C++ types, tons of numbers, uint32_t, int, etc. Sometimes what the compiler deduces for you is not accurate. Or specific, for that matter.
- Get the type for you, as easy as 1-2-3 (or not). So what if we had a variable with a type that's ambiguous, say for example, we had this function:
void do_work(auto &ref);
...we don't know the type, yeah? You could use templates, but this is another way to do it, really. That gets the type for you, then tells you what it is when the function is called.
Adding auto to any variable or whatever that deals with data types basically tells the compiler: "hey you! Get the type of this variable based on it's initializer", so if the initializer was a vector, deque, or something else, C++ will use that.
Fun fact: "Auto", according to Oxford Languages, also stands for "one's own." (so maybe the compiler really makes decisions).
Good resource for reading!: https://github.com/AnthonyCalandra/modern-cpp-features/blob/master/CPP11.md#auto.