Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of auto in C++11

Tags:

c++

c++11

auto

People also ask

What is Auto used for in C?

Auto is a storage class/ keyword in C Programming language which is used to declare a local variable. A local variable is a variable which is accessed only within a function, memory is allocated to the variable automatically on entering the function and is freed on leaving the function.

Does C++11 have auto?

C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.

Why do we use Auto?

The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.

Should I use Auto everywhere?

Use auto anywhere it makes writing code easier. Every new feature in any language is going to get overused by at least some types of programmers.


The difference is that in the first case auto is deduced to int* while in the second case auto is deduced to int, which results in both p1 and p2 being of type int*. The type deduction mechanism for auto is equivalent to that of template arguments. The type deduction in your example is therefore similar to

template<typename T>
void foo(T p1);

template<typename T>
void bar(T* p2);

int main()
{
    int i;
    foo(&i);
    bar(&i);
}

where both functions are instantiated as type void(int*) but in the first case T is deduced to int* while in the second case T has type int.


auto specifier used in declarations of variables, deduces its type with the same rules as used in template argument deduction.

Consider your first example (i.e., auto p1 = &i;). The type of auto specifier is deduced as follows:

  1. auto is replaced with an imaginary type template parameter (e.g., U p1 = &i;).
  2. &i type is int*, thus with no surprises and according to template deduction rules U is deduced to int*.

Now consider your second example (i.e., auto *p2 = &i).

  1. Again auto is replaced with an imaginary type template parameter (e.g., U* p1 = &i;).
  2. &i type is int*, thus according to template deduction rules U is deduced to int.

As such, in auto *p2 = &i; the placeholder type auto will correctly be deduced as int and not as int*, that would result in p2 being of type int**, as you might have expected.