Sunday, October 23, 2016

What does the keyword 'auto' signify in C++?

This post describes the use of auto keyword in C++ projects in Visual Studio 2015 Community.

The meaning of auto keyword depends. It depends on the version of C++ you are using.
Before C++ version 11 appeared it simply meant that the keyword auto together with the datatype signified that the scope of the variable with which it was used has automatic storage duration (same as local variable). The keyword auto in that sense was used to explicitly specify the local variable to have automatic storage duration.

With C++ 11 version auto has a different meaning. You need not specify what the variable datatype is, it is inferred by the value it is assigned.
For example, instead of saying:

int x=5;
i.e., the datatype of x is integer, you can just say,

auto x=5;

This is called automatic type deduction. One thing to note is that the variables have to be assigned a value then only automatic type deduction works.

So, no initialization, no automatic type deduction.

In C++ 14, the automatic type detection is available not only for variables with assigned values but also for return types of funcitons. Here isan example of auto retrun type. The project is a blank C++ project type in Visual Studio 2015.

c
plusplus14

There was an intention to include auto keyword to be associated with function parameters but it was dropped. Visual Studio 2015 Community supports most of C++ 14 features but does not support the auto keyword for the function parameters as seen here.


Cplusplus14_1

If you try to build the project anyway, you will end up with the following errors:


Cplusplus14_2




No comments: