Harold Serrano

View Original

Declaring variables with "auto" in C++

I wanted to share with you some of the concepts I have learned from C++ 11. One of the new features in C++ 11 is the automatic type deduction: auto. With auto you can declare a variable or an object without specifying its type.

For example:

auto i=12; //i is of type int
auto f=4.2; //f is of type float

How does auto knows what is the type of a variable? auto deduces the type from its initializer. Therefore, an initializer is required. The following example will produce an error:

auto i; // ERROR, it can't deduce its type

You can add additional qualifiers if you want such as:

static auto i=12;

Using auto is quite nice. You can use it when the type is complicated or pretty long. You just let the compiler deduce the type. For example:

vector<string> v;
//...
auto pos=v.begin(); //pos has type vector<string>::iterator

Use auto whenever you can, just make sure to provide an initializer so auto knows how to deduce the type.