What are auto and decltype in C++?


Auto is a keyword in C++11 and later that is used for automatic type deduction. Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. For example, you want to create an iterator to iterate over a vector, you can simply use auto for that purpose. 

example

#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<int> arr(10);
   for(auto it = arr.begin(); it != arr.end(); it ++) {
      cin >> *it;
   }
   return 0;
}

In the above program, it will automatically get the type std:: vector<int>:: iterator.

The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it. The value returned by decltype can directly be used to define another variable. For example, the above code can be written as the following using decltype −

Example

#include <iostream>
#include <vector>
using namespace std;
int main() {
   vector<int> arr(10);
   for (decltype(arr.begin()) it = arr.begin(); it != arr.end(); it++) {
      cin >> *it;
   }
   return 0;
}

Note that The type denoted by decltype can be different from the type deduced by auto. You can read more about these subtle differences in this 12-page explanation of type deduction in C++ −http://thbecker.net/articles/auto_and_decltype/section_01.html

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 11-Feb-2020

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements