C++ Automatic Type Deduction

Introduction

We can automatically deduce the type of an object using the auto specifier.

The auto specifier deduces the type of an object based on the object's initializer type.

Example:

auto c = 'a';    // char type 

This example deduces c to be of type char as the initializer 'a' is of type char.

Similarly, we can have:

auto x = 123;    // int type 

Here, the compiler deduces the x to be of type int because an integer literal 123 is of type int.

The type can also be deduced based on the type of expression:

auto d = 123.456 / 789.10;    // double 

This example deduces d to be of type double as the type of the entire 123.456 / 789.10 expression is double.

We can use auto as part of the reference type:

int main() 
{ 
    int x = 123; 
    auto& y = x; // y is of int& type 
} 

or as part of the constant type:

int main() 
{ 
    const auto x = 123; // x is of const int type 
} 

We use the auto specifier when the type (name) is hard to deduce manually or cumbersome to type due to the length.




PreviousNext

Related