Table of Contents
The decltype specifier allows the compiler to determine the data type of an expression without evaluating it. It is useful when the exact type of an expression is unknown, difficult to write, or depends on another variable.
Unlike auto, which deduces the type from an initializer, decltype determines the type from an existing expression. This makes it valuable when declaring variables, function return types, and template-based code.
Source Code #
#include <iostream>
int main()
{
int value = 100;
decltype(value) copy = 200;
std::cout << "Value: " << value << '\n';
std::cout << "Copy: " << copy << '\n';
return 0;
}
Output #
Value: 100
Copy: 200
Explanation #
decltype(value)determines the data type of the expressionvalue.- Since
valueis of typeint,copyis also declared as anint. - No value from
valueis copied during type deduction; only its type is used. decltypeexamines the expression at compile time without evaluating it.decltypeis commonly used when the exact type of an expression is not known in advance.std::coutdisplays the values stored in both variables.return 0;terminates the program successfully.