Automatic Type Inference Using auto
In some cases, 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 give you the option of not having to explicitly specify the variable type when using the keyword auto. In this example, we have left the task of defining an exact type for variable coinFlippedHeads to the compiler:
auto coinFlippedHeads = true;
The compiler checks the value the variable is being initialized to and then decides on the best possible type for 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 best suits variable coinFlippedHeads and internally treats coinFlippedHeads as a bool, as also demonstrated in Listing 3.6.
Input ▼
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); 11: cout << endl << "largeNumber = " << largeNumber << ", "; 12: cout << "sizeof(largeNumber) = " << sizeof(largeNumber) << endl; 13: 14: return 0; 15: }
Output ▼
coinFlippedHeads = 1, sizeof(coinFlippedHeads) = 1 largeNumber = 2500000000000, sizeof(largeNumber) = 8
Analysis ▼
Note the use of the auto keyword in Lines 6 and 7, where the two variables have been declared. By using auto, you delegate the decision on the type of variable to the compiler, which uses the initialization value as a ballpark. sizeof() is used in Lines 10 and 12 to check whether the compiler created the types it was expected to, and the output confirms that it really did.
Even if auto seems to be a trivial feature at first sight, it makes programming a lot easier in cases where the 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 later chapters.