The auto keyword was a way to explicitly specify that a variable should have automatic duration:
int main()
{
auto int foo(5); // explicitly specify that foo should have automatic duration
return 0;
}
Auto in C++ 11:
In C++11, the meaning of the auto keyword has changed, consider the following statement:
double d = 5.0;
Starting with C++11, When initializing a variable, the auto keyword can be used in place of the variable type to tell the compiler to infer the variable’s type from the initializer’s type. This is called type inference (also sometimes called type deduction).
For example:
auto d = 5.0; // 5.0 is a double literal, so d will be type double
auto i = 1 + 2; // 1 + 2 evaluates to an integer, so i will be type int
This even works with the return values from functions:
int add(int x, int y)
{
return x + y;
}
int main()
{
auto sum = add(5, 6); // add() returns an int, so sum will be type int
return 0;
}
Note:
1. Note that this only works when initializing a variable upon creation.
2. The auto keyword can’t be used with function parameters:
Many new programmers try something like this, This won’t work:
#include
void addAndPrint(auto x, auto y)
{
std::cout << x + y;
}
Type inference for functions in C++14 :
In C++14, the auto keyword was extended to be able to auto-deduce a function’s return type. Consider:
auto add(int x, int y)
{
return x + y;
}
Trailing return type syntax in C++11 :
C++11 also added the ability to use a trailing return syntax, where the return type is specified after the rest of the function prototype.
Consider the following function declaration:
int add(int x, int y);
In C++11, this could be equivalently written as:
auto add(int x, int y) -> int;
In this case, auto does not perform type inference
auto add(int x, int y) -> int;
auto divide(double x, double y) -> double;
auto printSomething() -> void;
auto calculateThis(int x, double d) -> std::string;
Comments
Post a Comment