auto keyword

Let us understand the usage of auto keyword with the help of an example.

#include <iostream>
using namespace std;

int main()
{
auto i = 10;
auto d = 7.5;
cout <<  “Integer and double: ” << i << “ “ << d << endl;
return 0;
}

Above code can be compiled using -std=c++11 flag.

Here, we have not defined the type for variable i and d. 
When we initialize the variable at the time of declaration, compiler can identify or deduce the type for it. Based on this, C++11 came with the concept of auto keyword.

auto keyword here tell the compiler to deduce the type according to the value assigned to it.

auto keyword is used to catch the return value of a function as well.

#include <iostream>
using namespace std;

int add(int a, int b)
{
return (a+b);
}

int main()
{
auto addValue = add(10,20);
cout << "Add value: " << addValue << endl;
return 0;
}

As you can see, auto keyword is used to hold the return value of add function. Since add function return type is int, so compiler can easily deduce the type for it.

Related posts