In C++, the auto
keyword forces the compiler to deduce a variable's type at compile time. So in this example
#include <vector>
int main()
{
std::vector<int> my_vec = {1, 2, 3};
auto my_vec_it = my_vec.begin();
return 0;
}
the compiler would deduce that my_vec_it
has type std::vector<int>::iterator
. I know this because replacing auto
with std::vector<int>::iterator
and recompiling produces the exact same executable.
I've found auto
to be handy in situations where the compiler doesn't agree with what I think a variable declaration should be, and I just want it to stop complaining so I can keep writing. In other words, I use auto
when I don't really understand the code I'm writing, and that seems like a bad habit. If the compiler and I disagree on a variable's type, that disagreement could percolate and cause more complicated, deeply-rooted errors further down in my code. That makes me wonder what the use auto
really is.
Is the use of auto
I describe above a bad programming practice, and if so what are some more principled uses of it?