C++ 11 auto keyword when to use


In this post, we are going to understand, What is C++ 11 auto keyword when to use with examples in C++ 11 and C++ 14.

What is ‘auto’ keyword in C++ 11

In C++, each variable requires a data type to be explicitly declared at compile time but with C++ 11, auto keyword is introduced to leave the type deduction to the compiler itself. Now the compiler deduces the types of variables at compile-time and developers will not need to specify it upfront.

The auto keyword is used to specify that the type of the variable which we are declaring will be automatically deducted from its initialized value.

Below are some of the examples using auto

auto pi = 3.14;             // double
auto num = 10;                // int
auto& refnum = num;           // int&

Uses of Auto keyword in C++ 11 and C++ 14

  • Variable Initialization
  • Function return types
  • Trailing return types
  • Function parameters

1. Most useful uses of auto keyword

Variable Initialization

It helped developers to avoid lengthy initializers typing like for containers below:

without auto keyword

In this example, we are not using auto keywords to define a variable

std::vector<int>::const_iterator cit = v.cbegin();  // Before auto

Using auto keyword

In this below example, we are not using auto keyword to define a variable

auto cit = v.cbegin(); // after auto in C++ 11

auto keyword in C++ 14

1.Function return types

Another good use of auto is for function return types which also eliminates the developer’s concerns of mistakes in return values types. But generally, this should be avoided to help developers see the return type upfront instead of checking the code and finding out.

// sum() returns a 'reference to int'
int& sum() {   }
auto m = sum(); // use of auto for function return type

2.Trailing return types

The ‘auto’ keyword can also be used for the functions with trailing return types as you can see in the below functions

auto add(int x, int y) -> int;
auto divide(double x, double y) -> double;

3.Function parameters

The ‘auto’ keyword can also be used for type inferences of parameters of a function. This is supported by C++ 20.

// only valid in C++20
void sum(auto x, auto y)
int main()
sum (4.5, 6.7);    // float

This helps developers to avoid templates and just simply use auto when they want to make functions for arguments with different data types.


In this post, we have understood C++ 11 auto keyword when to use auto and C++ 14 and important uses of it with examples