Type Inference in C++: auto and decltype



In this tutorial, we will be discussing a program to understand Type interference in C++ (auto and decltype).

In the case of auto keyword, the type of the variable is defined from the type of its initializer. Further, with decltype, it lets you extract the type of variable from the called element.

auto type Example

Here is the following example of auto-type in C++.

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

int main() {
  auto x = 4;
  auto y = 3.37;
  auto ptr = & x;

  cout << typeid(x).name() << endl <<
    typeid(y).name() << endl <<
    typeid(ptr).name() << endl;

  return 0;
}

Output

This is the following output for it.

i
d
Pi

decl type Example

Here is the following example of decl type in C++.

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

int fun1() {
  return 10;
}
char fun2() {
  return 'g';
}

int main() {
  decltype(fun1()) x;
  decltype(fun2()) y;

  cout << typeid(x).name() << endl;
  cout << typeid(y).name() << endl;

  return 0;
}

Output

This is the following output for it.

i
c
Updated on: 2024-12-03T22:12:18+05:30

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements