What is the auto keyword in C++?
Written by
auto keyword is used to avoid writing the data-type of a variable.
The compiler infers the data-type from its initializer.
Let us look at an example to get a clear understanding of the concept:
#include <iostream>
#include <typeinfo> //for typeid().name()
using namespace std;
int main(){
auto a = 4;
auto b = 'a';
auto ptr = &b;
cout << typeid(a).name() << "\n" << typeid(b).name() << "\n" << typeid(ptr).name() << "\n";
return 0;
}
Output:
i
c
Pc
typeid(x).name() returns a shorthand name for data-type of x. Here, the compiler automatically sets the data-type of the variables from the value they are assigned.
The auto keyword provides a number of benefits over the primitive method of data-type declaration:
- It is a simple way of declaring a variable of complicated data type
- If the expression’s type is changed—this includes when a function return type is changed—it just works.
- Your coding can be more efficient
NOTE: “auto” is a feature introduced in C++ 11. Hence, it isn’t available in C and previous versions of C++.