8.7 — Type deduction for objects using the auto keyword

There’s a subtle redundancy lurking in this simple variable definition:

Because C++ is a strongly-typed language, we are required to provide an explicit type for all objects. Thus, we’ve specified that variable d is of type double.

However, the literal value 5.0 used to initialize d also has type double (implicitly determined via the format of the literal).

Related content

We discuss how literal types are determined in lesson 4.13 -- Literals.

In cases where we want a variable and its initializer to have the same type, we’re effectively providing the same type information twice.

Type deduction for initialized variables

Type deduction (also sometimes called type inference) is a feature that allows the compiler to deduce the type of an object from the object’s initializer. To use type deduction, the auto keyword is used in place of the variable’s type:

In the first case, because 5.0 is a double literal, the compiler will deduce that variable d should be of type double. In the second case, the expression 1 + 2 yields an int result, so variable i will be of type int. In the third case, i was previously deduced to be of type int, so x will also be deduced to be of type int.

Because function calls are valid expressions, we can even use type deduction when our initializer is a function call:

The add() function returns an int value, so the compiler will deduce that variable sum should have type int.

Type deduction will not work for objects that do not have initializers or empty initializers. Thus, the following is not valid:

Although using type deduction for fundamental data types only saves a few (if any) keystrokes, in future lessons we will see examples where the types get complex and lengthy (and in some cases, can be hard to figure out). In those cases, using auto can save a lot of typing (and typos).

Type deduction drops const qualifiers

In most cases, type deduction will drop the const qualifier from deduced types. For example:

In the above example, x has type const int, but when deduction a type for variable y using x as the initializer, type deduction deduces the type as int, not const int.

If you want a deduced type to be const, you can use the const keyword in conjunction with the auto keyword:

In this example, the type deduced from x will be int (the const is dropped), but because we’ve re-added a const qualifier during the definition of variable y, variable y will be a const int.

For advanced readers

Type deduction will not drop the const qualifier for pointers to const values, such as types deduced from C-style string literals.

Type deduction drops references

For advanced readers

We haven’t covered references yet, but type deduction will also drop references.

For example, if you use type deduction with an initializer of type int&, the deduced type will be “int”, not “int&”.

You can ensure a deduced type is a reference type by using auto& instead of auto.

You can also deduce a const reference by using const auto&

Type deduction benefits and downsides

Type deduction is not only convenient, but also has a number of other benefits.

First, if two or more variables are defined on sequential lines, the names of the variables will be lined up, helping to increase readability:

Second, type deduction only works on variables that have initializers, so if you are in the habit of using type deduction, it can help avoid unintentionally uninitialized variables:

Third, you are guaranteed that there will be no unintended performance-impacting conversions:

Type deduction also has a few downsides.

First, type deduction obscures an object’s type information in the code. Although a good IDE should be able to show you the deduced type (e.g. when hovering a variable), it’s still a bit easier to make type-based mistakes when using type deduction.

For example:

In the above code, if we’d explicitly specified y as type double, y would have been a double even though we accidentally provided an int literal initializer. With type deduction, y will be deduced to be of type int.

Here’s another example:

In this example, it’s less clear that we’re getting an integer division rather than a floating-point division.

Second, if the type of an initializer changes, the type of a variable using type deduction will also change, perhaps unexpectedly. Consider:

If the return type of add changes from int to double, or gravity changes from int to double, sum will also change types from int to double.

For advanced readers

Third, because type deduction drops references, if you use “auto” when you should be using “auto&”, your code may not perform as well, or may even not work correctly.

Overall, the modern consensus is that type deduction is generally safe to use for objects, and that doing so can help make your code more readable by de-emphasizing type information so the logic of your code stands out better.

Best practice

Use type deduction for your variables, unless you need to commit to a specific type.

Author's note

In future lessons, we’ll continue to use explicit types instead of type deduction when we feel showing the type information is helpful to understanding a concept or example.

8.8 -- Type deduction for functions
8.6 -- Typedefs and type aliases

80 comments to 8.7 — Type deduction for objects using the auto keyword

  • Lumina

    Correct me if i am wrong, but i see deduction type as pure confusion, i literally don't see a point in using that. When u look through a complicated code, it sometimes becomes quite annoying to hover at each variable and see what type it is. Imo, declaring type as it is, improves readability much much more... at least for me.

    Or i don't understand smth? o.o

    • Alex

      As you get into more advanced C++ (where most code uses classes and templates), the focus tends to be more on emphasizing what the code is doing rather than being super explicit about what type everything is.

      But by all means, be explicit though wherever you think it's useful for comprehension/documentation, especially for fundamental types.

      • Lumina

        Thanks for response!
        Great tutorial btw ^^ Keep it up!
        Haven't touched C++ for 10 years, now catching up again due to urgent need x.x

  • beaners

    Hello, in the tutorial: Type deduction for objects using the auto keyword. There is a small but can be quite confusing word which is readded

    "In this example, the type deduced from x will be int (the const is dropped), but because we’ve readded a const qualifier during the definition of variable y, variable y will be a const int."

    There is no word called readded and its closest word readed doesn't fit into this context. The optimal word is re-added. Thanks for your amazing tutorials

  • teod

    I think

    was meant to say "y will be type const int"

  • Hi

    Will auto ever make a variable an std::string or std::vector, etc.?

  • SuperNoob

    I have a question. In python, there is a function called "type()" which resolves the type of an input. For example:

    <class 'str'>

    Means "hello" is an object of the string class. Is there any similar method in c++?

    • nascardriver

      The return value of `name()` is implementation-defined. You can't use it for anything other than debugging.

  • Sahil

    Hello, I just wanted to know if we should be using function templets or the auto type deduction to make functions more flexible. Which one is preferred more starting C++20, also would using type deduction create portability issues? since not every one will be using a compiler that implements C++20 as its still fairly new.


  • J34NP3T3R

    i cant remember where to change or update my current C++ version to C++20

  • Patrick

    For this line of code in your last example -

    You guys said "this use of auto does not perform type inference", but it looks like it does. Is there something I'm not getting?

    • Alex

      I'm not sure what I was thinking when I wrote that. I've removed it for the time being.

      The way C++ handles type deduction for auto variables is substantially similar to how it deduces types for templates.\

      Thanks for the feedback.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]