Type Inference in C++ (auto and decltype) (original) (raw)

Last Updated : 13 Jun, 2026

Type inference is a feature introduced in modern C++ that allows the compiler to automatically determine the type of a variable or expression. It reduces code verbosity and makes programs easier to write and maintain.

Type Inference Using auto

The auto keyword instructs the compiler to automatically deduce the type of a variable from the value used to initialize it.

Syntax

auto variable_name = value;

C++ `

#include using namespace std;

int main() { auto x = 10; auto y = 3.14; auto z = 'A';

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

return 0;

}

`

**Explanation

Using auto with Complex Types

auto is especially useful when working with iterators, templates, and long type names.

C++ `

#include #include using namespace std;

int main() { vector v = {1, 2, 3, 4};

for (auto it = v.begin(); it != v.end(); ++it) {
    cout << *it << " ";
}

return 0;

}

`

**Explanation: The compiler automatically deduces the iterator type returned by v.begin(), avoiding the need to write the full iterator declaration.

Type Inference Using decltype

The decltype keyword determines the type of an expression at compile time and uses that type for variable declarations.

Syntax

decltype(expression) variable_name;

**where:

#include using namespace std;

int main() { int x = 10;

decltype(x) y = 20;

cout << y;

return 0;

}

`

**Explanation: Since x is of type int, decltype(x) is also int, so y becomes an integer variable.

Combining auto and decltype

auto and decltype are often used together in generic programming and template-based code.

C++ `

#include using namespace std;

template <typename T, typename U> auto add(T a, U b) -> decltype(a + b) { return a + b; }

int main() { cout << add(10, 5.5);

return 0;

}

`

**Explanation

Advantages of Type Inference

Type inference helps simplify code and improve readability.

Limitations of Type Inference

Although useful, type inference should be used carefully.