Prior to C++11, the auto keyword was probably the least used keyword in C++. The auto keyword was a way to explicitly specify that a variable should have automatic duration. In this post i want discuss about auto keyword.

You learned that local variables have automatic duration (they’re created at the point of definition, and destroyed when the block they are part of is exited).Auto keyword explicitly specify that foo should have automatic duration. However, since all variables in modern C++ default to automatic duration unless otherwise specified, the auto keyword was superfluous, and thus obsolete.

{
auto int foo(5); // explicitly specify that foo should have automatic duration

return 0;
}

Type inference in C++11

In C++11, the meaning of the auto keyword has changed, and it is now a useful addition to your C++ vocabulary.

Consider the following statement:

double d = 5.0;

If C++ already knows 5.0 is a double literal, why do we have to explicitly specify that d is actually a double? Wouldn’t it be nice if we could tell a variable to just assume the proper type based on the value we’re initializing it with?

Starting with C++11, the auto keyword does just that. 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;
}

The auto keyword can’t be used with function parameters

Many new programmers try something like this:


#include <iostream>

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;
}

 

Tags , , , , , , , , , , , , , , , , , ,


Leave a Reply

Want to see your ugly mug by your comment? Get a free custom avatar at Gravatar.