Auto and var types do have a type. The compiler will figure out what that is.

You might think this is just a shortcut and it sometimes helps cut down on the typing. But there are other benefits.

Let’s say you have a method that’s declared to return an int. And you want to create a local int variable to hold the result of calling this method. You could start out by declaring an int variable, giving it a name, and initializing it with the return value from calling the method. But what if you declared a local string variable and tried to initialize it with the same result of calling the method?

The compiler will give you an error. It knows the types int and string aren’t compatible. Now, if the compiler knows when there’s a mismatch, then it’s not very hard to imagine that the compiler could just figure out the type of the local variable itself. You don’t have to tell the compiler what type the variable should be.

In this case, the auto variable really is an int. The compiler is able to figure out the type because of how it gets initialized. You can’t just declare an auto variable and leave it uninitialized. You also can’t declare an auto variable and expect it to be some other type that doesn’t match.

This feature may not seem very remarkable yet. That’s just because the examples have been simple. The benefits of auto tend to increase as the difficulty of determining the type needed also increases. What if instead of a simple int return type from a method, that method is passed a collection as one of its parameters. And inside the method, you want to iterate through the items in that collection. You’ll need to declare the proper iterator type and assign that iterator the value you get from calling begin. This is just a more complicated return type than the simple example method that returned an int. But the same principle applies. This time, it really does save you some typing.

What you need to remember is that code changes. All the time. Especially during initial development. By using auto, you actually help isolate your code from changes. Let’s say that collection starts out as a vector of ints and later needs to change to a map of ints and some custom class. If you coded the iterator type explicitly needed to work with a vector of ints, then it’s going to have to change when the collection type changes. But if you took the easy way and used auto, then guess what? It can remain auto with the new collection. Sure, some of the code might have to change. After all, going from a vector to a map is a big change. But why not let the compiler do at least some of the work for you?

Listen to the episode for some more benefits of using auto or var to declare your variables.