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.
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.
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.
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:
auto
is replaced with an imaginary type template parameter (e.g., U p1 = &i;
).&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
).
auto
is replaced with an imaginary type template parameter (e.g., U* p1 = &i;
).&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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With