C/C++ and Fortran

 View Only

C++11 new feature: auto type deduction

By Archive User posted Wed April 17, 2013 02:32 AM

  

Originally posted by: FangLu


 In the C++11 standard, the auto keyword is no longer a storage class specifier, but acts as a type specifier that directs the compiler to deduce the type of a declared variable from its initialization expression.

 

With the auto type deduction feature enabled, you no longer need to specify a type while declaring a variable. Instead, the compiler deduces the type of an auto variable from the type of its initializer expression. For example:

auto i = 1.1;    // i : double

 

You can also qualify the auto keyword with cv-qualifiers, pointer(*) and reference(&) declarators. For example:

double* pd;

auto x = pd;     // x : double*

auto* y = pd;    // y : double*

 int g();

auto x = g();          // x : int

const auto& y = g();   // y : const int&

 

You can also declare multiple variables in a single auto declaration statement. For example:

auto x = 1.2, y = 3.9;     // x : double, y : double

 

In case of multiple variable declarations, the type of each declarator can be deduced independently. If the deduced type is not the same in each deduction, the program is ill-formed. For example, in the following statement, y is deduced as double, but was previously deduced as int.

auto x = 3, y = 1.2;      //error

 

auto can be applied to the new expression. For example:

auto* p = new auto(1);    // p : int *

 

auto cannot deduce array types. For example:

char a[5];

auto b[5] = a;      // error, a evaluates to a pointer, which does

                    // not match the array type

 

 auto can not be used in function parameters. For example: 

int func(auto x = 3);      //error, parameter declared 'auto'

 

From the previous examples, we can see that the auto type deduction feature can increases programming convenience, potentially eliminates typing errors, and simplifies your code.

2 comments
1 view

Permalink

Comments

Fri July 12, 2013 04:12 PM

Originally posted by: ShafikYaghmour


There is a very interesting case where auto deduces differently then expected: int val = 0 ; auto a { val } ; In this case a will be deduced as a std::initializer_list

Wed July 10, 2013 11:38 AM

Originally posted by: ShafikYaghmour


You left out what many are calling the new most vexing parse, for example: int val = 0; auto a { val }; will deduce: std::initializer_list