auto keyword
It is old keyword of c language, we can use it for defining a variable or object without specifying type in c++11.
We can define auto having integer
auto i = 10; std::cout<<"i:"<<i<<" Data type:"<<typeid(i).name()<<std::endl;
We can define auto having double
auto ii(10.6); std::cout<<"ii:"<<ii<<" Data type:"<<typeid(ii).name()<<std::endl;
We can define auto having std::string
auto iii{"auto string"}; //this is uniform initialisation std::cout<<"iii:"<<iii<<" Data type:"<<typeid(iii).name()<<std::endl;
We can define auto having function return type
auto r = fun1(); std::cout<<"r:"<<r<<" Data type:"<<typeid(r).name()<<std::endl;
We can define auto having vector object
std::vector<int>v{1, 2, 3, 4}; //this is uniform initialisation auto av = v; std::cout<<"av:"<<" Data type:"<<typeid(av).name()<<std::endl;
Advantages:
- Less Error Prone, because initialisation is MUST for auto so we can get ride from uninitialised variable problem.
auto a; //we will get below error //auto.cpp:16:10: error: declaration of ‘auto a’ has no initializer auto a = 5; //It must be initialized
- Less writing effort, because we can collect iterator deceleration in single auto var
std::vector<int>::iterator itr = v.begin(); //we can reduce writing effort, same iterator we can collect in auto auto s = v.begin(); std::cout<<"s:"<<*s<<" Data type:"<<typeid(s).name()<<std::endl;
Complete source code with examples:
#include<iostream> #include<typeinfo> #include<vector> std::string fun1() { return("dummy function"); } int main() { std::cout<<"Auto C++11"<<std::endl; //1. you can define the variable without specifying data type auto i = 10; std::cout<<"i:"<<i<<" Data type:"<<typeid(i).name()<<std::endl; auto ii(10.6); std::cout<<"ii:"<<ii<<" Data type:"<<typeid(ii).name()<<std::endl; auto iii{"auto string"}; //this is uniform initialization std::cout<<"iii:"<<iii<<" Data type:"<<typeid(iii).name()<<std::endl; //Auto MUST be intialized //if do like this --> auto a; //you will get below error //auto.cpp:16:10: error: declaration of ‘auto a’ has no initializer //2. we can collect the Function return type auto r = fun1(); std::cout<<"r:"<<r<<" Data type:"<<typeid(r).name()<<std::endl; //3. we can collect stl types also std::vector<int>v{1, 2, 3, 4}; //this is uniform initialization auto av = v; std::cout<<"av:"<<" Data type:"<<typeid(av).name()<<std::endl; std::vector<int>::iterator itr = v.begin(); //we can reduce writing effort, same iterator we can collect in auto auto s = v.begin(); std::cout<<"s:"<<*s<<" Data type:"<<typeid(s).name()<<std::endl; return 0; }
Compilation command:
g++ -std=c++11 ./auto.cpp
Output:
Auto C++11 i:10 Data type:i ii:10.6 Data type:d iii:auto string Data type:PKc r:dummy function Data type:NSt7__cxx1112basic_stringIcSt11char av: Data type:St6vectorIiSaIiEE s:1 Data type:N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE