Automatic Type Deduction (auto & decltype)

🔴 Advanced

📖 Definition

Introduced in C++11, auto deduces variable types at compile time from their initializer expressions. decltype(expr) inspects and yields the exact declared type of an expression without evaluating it.

💡 Code Example

#include <iostream>
#include <vector>

int main() {
    auto x = 42; // Deduces int
    std::vector<double> v{1.1, 2.2};
    auto it = v.begin(); // Deduces std::vector<double>::iterator

    decltype(x) y = 100; // y is int

    std::cout << "x: " << x << ", *it: " << *it << ", y: " << y << "\n";
    return 0;
}