auto

Changes to auto in C++11

In C++11, the keyword auto is used for automatic type deduction. But in C and in prior versions of C++, auto has an entirely different meaning. It’s used to explicitly identify a variable as having automatic storage:

int foo ()
{
  auto int iX; // iX has automatic storage
  ...
}

Because programmers can use the auto keyword only with variables that are already automatic by default, they rarely bother using it. Its main function is to document that you really wanted to use a local automatic variable. In C++11, this usage no longer is valid.

New meaning of keyword auto

Specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type.
When declaring variables in a scope of function or in namespace scope, in initialization statements and etc, the type of the variable may be omitted and the keyword “auto” may be used instead.  Once the type of the initializer has been determined, the C++11  compiler sets the type of the variable to the type of the initialization value:

#include <iostream>

int main()
{
  auto x = 1 + 2;
  auto y = &x;

  std::cout << "type of x: " << typeid(x).name() << '\n';
  std::cout << "type of y: " << typeid(y).name() << '\n';

  return 0;
}

Output:
auto1
For example, we can define a pointer to a function in the following way:

#include <iostream>

double Add( int x, float y)
{
 double aa = x + y;
 return  aa ;
}

int main()
{
 auto pFun = Add;
 std::cout << "type of pFun: " << typeid(pFun).name() << '\n';

 return 0;
}

Output:
auto2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s