C++ 11 standard made lot many improvements to C++. New
features like rvalue reference, lambda functions, auto variable and many more
added to C++. There was auto variable in previous C++ also, but that has
completely new meaning now. C++ 11 standard committee members, which also includes
big organizations like, Microsoft, Apple, Google, IBM, decided C++98 auto variable
is pretty useless, and new meaning can be given to auto keyword with little
impact.
In this article we will discuss about auto variables.
Let’s start simple first,
int i = 10;
auto a = 10;
cout<<typeid(i).name() << " "<<typeid(a).name()<<endl;// int int
We have explicitly mentioned ‘i’ as integer. For variable
‘a’ we left to compiler to decide its type.
As 10 is integer, type of a would be int. So cout will print ‘int int’ as
output.
Let’s take bit complex example,
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
//print all elements of
vector -- old C++ way
for(vector<int>::iterator it = v.begin();it!= v.end(); it++)
{
cout<<*it;
}
//print all elements of
vector -- used C++ 11 auto
for(auto it = v.begin(); it != v.end(); it++)
{
cout<<*it;
}
You can see how clumsy looking iterator variable definition
can be easily replaced by auto keyword. You need not to explicitly specify
which container you are using, and no need to remember what it contains, just v.begin() tells compiler its type.
At very least it makes code look cleaner.
One thing I wanted to bring to notice that C++ is statically
typed language, and compiler has to know data type of object at compile time.
So, data type of auto variables will also be decided at compile time only.
There are more concrete reasons to use
auto variable with lambda functions that I will cover in article for lambda
functions.
If you have any queries or suggestions, please put comments
below.