auto and decltype in C++
auto (modernized in C++11) asks the compiler to deduce a variable's type from its initializer: auto x = 5; makes x an int without you spelling it out. It shines with long iterator and template types that are painful to write by hand, and it guarantees the variable's type exactly matches the expression — no accidental narrowing or mismatch.
decltype goes one step further: it queries an expression's type without evaluating it, mostly for generic code. decltype(x + y) is the declared type of that sum, letting templates declare correctly-typed locals and return values from expressions they haven't seen yet.
auto deduces from the initializer
auto x = 5; gives int, auto name = std::string("a"); gives std::string — deduction follows the same rules as template type deduction.
Always initialize with auto
auto x; is a compile error — with no initializer there is nothing to deduce from, which conveniently outlaws uninitialized variables.
Watch reference and const dropping
auto chops top-level references and const, so auto& and const auto& exist for when you need the original qualifiers back.
decltype for unevaluated queries
decltype(expr) yields expr's type without running it — the tool templates use to name types computed from other types.
#include <iostream>#include <vector> int main() { auto count = 42; std::vector<int> v{1, 2, 3}; auto it = v.begin(); decltype(count) total = 0; std::cout << count << ", " << *it << ", " << total << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.