Home > Articles

  • Print
  • + Share This
This chapter is from the book

Automatic Type Inference Using auto

There are cases where the type of a variable is apparent given the initialization value being assigned to it. For example, if a variable is being initialized with the value true, the type of the variable can be best estimated as bool. Compilers supporting C++11 and beyond give you the option of not having to explicitly specify the variable type when using the keyword auto.

auto coinFlippedHeads = true;

We have left the task of defining an exact type for variable coinFlippedHeads to the compiler. The compiler checks the nature of the value the variable is being initialized to and then decides on the best possible type that suits this variable. In this particular case, it is clear that an initialization value of true best suits a variable that is of type bool. The compiler thus determines bool as the type that suits variable coinFlipped-Heads best and internally treats coinFlippedHeads as a bool, as also demonstrated by Listing 3.6.

LISTING 3.6 Using the auto Keyword and Relying on the Compiler’s Type-Inference Capabilities

  1: #include <iostream>
  2: using namespace std;
  3:
  4: int main()
  5: {
  6:    auto coinFlippedHeads = true;
  7:    auto largeNumber = 2500000000000;
  8:
  9:    cout << "coinFlippedHeads = " << coinFlippedHeads;
 10:    cout << " , sizeof(coinFlippedHeads) = " << sizeof(coinFlippedHeads) <<
 endl;
 11:    cout << "largeNumber = " << largeNumber;
 12:    cout << " , sizeof(largeNumber) = " << sizeof(largeNumber) << endl;
 13:
 14:    return 0;
 15: }

Output arrow.jpg

coinFlippedHeads = 1 , sizeof(coinFlippedHeads) = 1
largeNumber = 2500000000000 , sizeof(largeNumber) = 8

Analysis arrow.jpg

See how instead of deciding that coinFlippedHeads should be of type bool or that largeNumber should be a long long, you have used the auto keyword in Lines 6 and 7 where the two variables have been declared. This delegates the decision on the type of variable to the compiler, which uses the initialization value as a ballpark. You have used sizeof to actually check whether the compiler created the types you suspected it would, and you can check against the output produced by your code to verify that it really did.

Even if auto seems to be a trivial feature at first sight, it makes programming a lot easier in those cases where the type variable is a complex type. The role of auto in writing simpler, yet type-safe code is revisited in Lesson 15, “An Introduction to the Standard Template Library,” and beyond.

  • + Share This
  • 🔖 Save To Your Account