Auto keyword in C++
The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by looking into the initialization. So, it is good to declare the variable with the auto keyword. There are so many uses of auto keywords. These are variables, functions, pointers, iterators, templates, and many more.
Syntax:
map <int, int>::iterator itr;
How Does The Auto Keyword Work?
We discussed above that it automatically assigns and detects the value of the data type. It means we can replace the variable with auto keywords and the auto keyword has no limits.
Auto Used with Variables
The Auto keyword has the feature of automatically detecting the variable data type. The compiler will know the type of data type by looking into initialization.
Syntax
auto var = 5;
Example 1
#include <iostream>
#include <typeinfo>
#include <map>
#include <string>
#include <iterator>
auto sum(int x, int y) -> int
{
return x + y;
}
int main()
{
// Storing an int inside an auto variable
auto var_1 = 10;
// Storing a character inside an auto variable
auto var_2 = 'D';
std::cout << var_1 << std::endl;
std::cout << var_2 << std::endl;
// Storing Lambda function inside an auto variable
auto fun_sum = [](int a , int b)
{
return a+b;
};
std::cout << fun_sum(4, 5) << std::endl;
std::map<std::string, std::string> mapOfStrs;
// Insert data in Map
mapOfStrs.insert(std::pair<std::string, std::string>("first", "1"));
mapOfStrs.insert(std::pair<std::string, std::string>("sec", "2"));
mapOfStrs.insert(std::pair<std::string, std::string>("thirs", "3"));
// Iterate over the map and display all data;
// Create an iterator
std::map<std::string, std::string>::iterator it = mapOfStrs.begin();
while (it != mapOfStrs.end())
{
std::cout << it->first <<"::"<< it->second << std::endl;
it++;
}
// Iterate using auto
auto itr = mapOfStrs.begin();
while (itr != mapOfStrs.end())
{
std::cout << itr->first <<"::"<< itr->second << std::endl;
itr++;
}
auto x = 1;
// Cannot change the type of already initialized auto variable
// Error will occur at compile time
// x = "dummy";
// Can not declare an auto variable without initialization
// because its type is based on initializing value.
//auto a;
auto value = sum(3, 5);
std::cout << value << std::endl;
return 0;
}
Output:
10
D
9
first::1
sec::2
thirs::3
first::1
sec::2
thirs::3
8
Example 2
#include <iostream>
using namespace std;
// declare function with auto return type
auto add(int p, int q) {
// variable to store the sum
int sum = p + q;
// return the calculated sum
return sum;
}
int main() {
// initialize variables
int p = 6, q = 5;
// call function to add the variables
int sum = add(p, q);
// print sum
cout <<"The sum is "<< sum << endl;
return 0;
}
Output:
The sum is 11