TeachMate
My ProgressJoin Session

Modern C++

0/8 completed · ~0h 31m

All Topics
C++LearnModern C++
1 / 8

auto Keyword

intermediate
3 min read

The auto keyword lets the compiler deduce the type automatically.

Basic Usage

auto x = 42;        // int
auto y = 3.14;      // double
auto s = "hello";   // const char*
auto z = 5.0f;      // float

When auto is Useful

auto it = v.begin();  // Complex iterator type
auto lambda = [](int x) { return x * 2; };  // Lambda type
auto result = func();  // Unknown return type

auto with References

auto& ref = x;     // Reference to x
const auto& cref = x;  // Const reference

auto with Pointers

auto p = &x;        // int*
auto sp = make_shared<int>(42);  // shared_ptr<int>

auto for Loop

auto nums = {1, 2, 3, 4, 5};
for (auto x : nums) {
    cout << x;
}

Structured Bindings (C++17)

auto [name, age] = pair("Alice", 20);
auto [x, y, z] = tuple(1, 2.0, "three");

When NOT to Use auto

  • When type is not obvious from context
  • When you need a specific type
  • In function signatures (use explicit types)
// Bad: what type is x?
auto x = func();

// Good: type is obvious
auto v = vector<int>(10);  // Obviously vector<int>
auto it = v.begin();      // Obviously iterator

Common mistakes: auto drops qualifiers and references, so auto x = obj silently copies instead of binding (use auto& or const auto&); auto also deduces proxy types such as vector<bool>::reference rather than bool.

Key takeaway: auto deduces types from initializers — use it when the type is obvious from context, not for function signatures.

Try it: Use auto for a variable, for an iterator over a vector, and in a range-based for loop, then print each value.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects