VOOZH about

URL: https://www.geeksforgeeks.org/cpp/type-inference-in-c-auto-and-decltype/

⇱ Type Inference in C++ (auto and decltype) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Type Inference in C++ (auto and decltype)

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.

  • auto deduces the type of a variable from its initializer.
  • decltype determines the type of an expression without evaluating it.
  • Commonly used in generic programming and template-based code.

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;


Output
10
3.14
A

Explanation

  • x is deduced as int.
  • y is deduced as double.
  • z is deduced as char.

Using auto with Complex Types

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


Output
1 2 3 4 

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:

  • expression is used only for type deduction.
  • variable_name is declared with the deduced type.

Output
20

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.


Output
15.5

Explanation

  • decltype(a + b) determines the return type of the function.
  • The compiler automatically deduces the correct type based on the operands.

Advantages of Type Inference

Type inference helps simplify code and improve readability.

  • Reduces the need to write lengthy type declarations.
  • Makes template and generic code easier to write.
  • Automatically adapts to type changes during maintenance.
  • Improves readability when working with complex types.

Limitations of Type Inference

Although useful, type inference should be used carefully.

  • Excessive use of auto can reduce code clarity.
  • The deduced type may not always be obvious to readers.
  • Incorrect assumptions about deduced types can lead to subtle bugs.
Comment
Article Tags: