C++ · Module 2 · Lesson 31 min read

auto & Type Deduction

auto

auto tells the compiler to deduce the type from the initializer:

ini
auto count = 10;        // int
auto price = 99.5;      // double
auto initial = 'A';     // char
auto ok = true;         // bool
auto big = 10LL;        // long long

The type is still fixed at compile time — C++ stays statically typed.

Rules

  • auto requires an initializer: auto x; is an error
  • auto drops const and references from the initializer: use const auto& when you want them
  • auto s = "hi"; gives const char*, not std::string! Use std::string s = "hi"; or auto s = "hi"s; (with using namespace std::string_literals)

Where auto shines

  • Long type names, especially iterators:
c
std::map<std::string, std::vector<int>>::iterator it = m.begin();   // 😩
auto it = m.begin();                                               // 😊
  • Range-based for loops: for (const auto& item : items)
  • Lambdas (their type has no name you can write)

Where to avoid auto

  • When the type isn't obvious and matters: auto x = get_value(); — is it int? double?
  • Simple declarations where the type helps readers: int count = 0;

decltype

decltype(expr) gives the type of an expression without evaluating it:

ini
int a = 5;
decltype(a) b = 10;   // b is int

Checking a type

sizeof and type traits like std::is_same_v<decltype(x), double> (Unit 12) let you confirm what was deduced.

Example

C++
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

int main() {
    auto count = 10;
    auto price = 99.5;
    auto letter = 'Z';
    auto literal = "hello";                 // const char*, not std::string!
    std::string name = "Ravi";
    auto copy = name;                       // std::string

    std::cout << std::boolalpha;
    std::cout << "count is int?      " << std::is_same_v<decltype(count), int> << '\n';
    std::cout << "price is double?   " << std::is_same_v<decltype(price), double> << '\n';
    std::cout << "letter is char?    " << std::is_same_v<decltype(letter), char> << '\n';
    std::cout << "literal is string? " << std::is_same_v<decltype(literal), std::string> << '\n';
    std::cout << "copy is string?    " << std::is_same_v<decltype(copy), std::string> << '\n';

    std::vector<double> expenses = { 850.5, 1200.0, 300.25 };
    double total = 0;
    for (auto e : expenses) total += e;     // auto -> double
    std::cout << "total = " << total << '\n';

    decltype(count) another = 7;            // same type as count (int)
    std::cout << "another + count = " << another + count << '\n';
    return 0;
}

/* Output:
count is int?      true
price is double?   true
letter is char?    true
literal is string? false
copy is string?    true
total = 2350.75
another + count = 17
*/