In this article we will learn how to use auto variable in C++11.

auto is introduces in C++11. With auto we can declare a variable without specifying its type. Its type will be deduced by the data to which its initializing i.e.

Here type of var_1 will be int and type of var_1 will be char.


We can story ant type in auto even if its a function or some iterator. Storing Lambda function inside a auto variable,

Main advantage of auto comes with types that are long to write i.e. Suppose we have a std::map of std::string & std::string i.e.

Now we want to iterate over the map and display its content using iterator. To declare an iterator of this kind of map we need to write,

Instead of typing std::map<std::string, std::string>::iterator  we can just use auto here i.e.

Important points about auto variable in C++11

1.) Once you have initialized the auto variable then you can change the value but you cannot change the type i.e.

2.) It cannot be left uninitialized i.e.

Returning an auto from a function

To return an auto variable from a function we need to declare it in a special way i.e.

Calling this function that returns auto,

Complete executable code is as follows,


Click Here to Subscribe for more Articles / Tutorials like this.