auto & Type Deduction
auto
auto tells the compiler to deduce the type from the initializer:
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
autorequires an initializer:auto x;is an errorautodropsconstand references from the initializer: useconst auto&when you want themauto s = "hi";givesconst char*, notstd::string! Usestd::string s = "hi";orauto s = "hi"s;(withusing namespace std::string_literals)
Where auto shines
- Long type names, especially iterators:
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:
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
#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
*/