The auto Keyword in C++ Used for Type Inference

Suraj P Oct 12, 2023
  1. the auto Keyword in C++
  2. Use auto With Functions in C++
  3. Use auto With Variables in C++
  4. Use auto With Iterators in C++
  5. Use auto With Function Parameters in C++
  6. Mistakes in Using auto Keyword in C++
  7. Conclusion
The auto Keyword in C++ Used for Type Inference

This tutorial will tackle the auto keyword introduced in C++ 11. We will look at different examples to understand its use cases and common mistakes done while using it.

the auto Keyword in C++

The keyword auto in the C++ 11 version is a part of the Type inference feature. Type inference means deducing the data type of function or a variable at compile time.

So we don’t have to specify the data type compiler can infer it automatically at compile-time. The return statement helps us infer the return data type for the functions.

Whereas, in the case of variables, the initialization helps determine the data type.

Use auto With Functions in C++

#include <iostream>
using namespace std;

auto division() {
  double a = 55.0;
  double b = 6.0;
  double ans = a / b;
  return ans;
}

int main() { cout << division(); }

Output:

9.16667

Here the return statement helps the compiler infer the return type of our division() function. Since the function returns ans, a double type, the compiler infers that auto must be replaced by a double.

Use auto With Variables in C++

#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
  auto x = 10;
  auto y = 10.4;
  auto z = "iron man";

  cout << x << endl;
  cout << y << endl;
  cout << z << endl;
}

Output:

10
10.4
iron man

Based on the right side of the statement, also called initializers, the compiler infers the type of variable.

Use auto With Iterators in C++

When dealing with STL containers like vector, set, or map, the auto keyword is highly used to iterate over them. We can minimize the loss of time by skipping the lengthy declaration of the iterator.

#include <bits/stdc++.h>
using namespace std;

int main() {
  vector<int> v{22, 14, 15, 16};

  vector<int>::iterator it = v.begin();  // without auto
  auto it2 = v.begin();

  while (it2 != v.end()) {
    cout << *it2 << " ";
    it2++;
  }
  cout << endl;

  map<int, int> mp;
  mp.insert(pair<int, int>(1, 40));
  mp.insert(pair<int, int>(2, 30));
  mp.insert(pair<int, int>(3, 60));
  mp.insert(pair<int, int>(4, 20));

  map<int, int>::iterator vt = mp.begin();  // without auto
  auto vt2 = mp.begin();

  while (vt2 != mp.end()) {
    cout << vt2->first << " -> " << vt2->second << endl;
    vt2++;
  }
  cout << endl;
}

Output:

22 14 15 16
1 -> 40
2 -> 30
3 -> 60
4 -> 20

We observe the difference between using the auto and not. Without auto, we have to explicitly specify the type of iterator, which is tedious as the statements are quite lengthy.

Use auto With Function Parameters in C++

In C++, we must specify the function parameters every time, but this can be simplified by using auto.

#include <bits/stdc++.h>
using namespace std;

void myfunc(auto x, auto str) { cout << x << " " << str << endl; }

int main() {
  int x = 10;
  string str = "Iron Man";
  myfunc(x, str);
}

Output:

10 Iron Man

The deduction of data types happens during the function call. Consequently, the matching of variables occurs, and the compiler figures out the exact data types for all the arguments.

Mistakes in Using auto Keyword in C++

Integer vs Boolean Confusion

In C++, we know that Boolean values are initialized as 0 or 1. Now, this might create some confusion while debugging.

#include <bits/stdc++.h>
using namespace std;

int main() { auto temp = 0; }

Multiple Declarations Using auto Keyword

We declare variables in a single go to save time, but this might create issues if both are of different types.

#include <bits/stdc++.h>
using namespace std;

int main() { auto x = 10, y = 35.66; }

Output:

[Error] inconsistent deduction for 'auto': 'int' and then 'double'

When we compile the above code in a compiler, we get an error, and this happens because the compiler gets confused.

Conclusion

We understood that the auto keyword saves a lot of time spent writing basic code, focusing on the more intensive and complex parts of a program. Though highly useful, we have to be careful how we use it.

Author: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub