Daily C++: Automatic variable types (auto type inference)

One of the nicest improvements when it comes to productivity is the introduction of the new meaning for the auto keyword. This is no different from the var of C#, makes code easier to write, yet sometimes slightly harder to understand.

The type inference is done by using auto in front of a variable name whose type can be automatically detected from context.

As you can see from the example above, auto stands for the type that can be detected from the right hand side of the assignment operation. So just having a variable of type auto will not work.

For a more complex usage of the type inference.

The output of this program will be:

References have to be specified – no automatic variable will be created as a reference, If the & is not used, a copy will be made instead.

This is a fun feature, as well as a possible issue. The types of the variables can be hard to track down at some point, and it makes the code more obfuscated, harder to understand. My suggestion would be to use the type inference when you don’t really need to know the type, or it’s obvious. One such example would be the use of iterators, but generally template based code will benefit a lot from the automatic types.

Comments are closed.