What does an auto keyword do in C++?

Auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used. All this changed with the introduction of auto to do type deduction from the context in C++11. Before C++ 11, each data type needs to be explicitly declared at compile time, limiting the values of an expression at runtime but after a new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself.

With type inference capabilities, we can spend less time having to write out things compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the runtime of the program.

The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.


using namespace std;

int main() {
   vector<int> vec(10);       // Auto deduce type to be iterator of a vector of ints.
   for(auto it = vec.begin(); it != vec.end(); vec ++)
      cin >> *it;
   return 0;