• Home
  • 1.21 decltype

1.21 decltype

View Categories

1.21 decltype

< 1 min read

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 expression value.
  • Since value is of type int, copy is also declared as an int.
  • No value from value is copied during type deduction; only its type is used.
  • decltype examines the expression at compile time without evaluating it.
  • decltype is commonly used when the exact type of an expression is not known in advance.
  • std::cout displays the values stored in both variables.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *