Auto Keyword
Type inference with auto
Interview Relevant: Modern C++ feature
Auto Keyword
The auto keyword (C++11) lets the compiler deduce the type from the initializer.
When to Use Auto
- Complex types: Iterators, lambda types
- Template code: When type depends on template parameters
- Return type deduction: auto return type (C++14)
Related Keywords
- decltype: Get the declared type of an expression
- decltype(auto): Perfect forwarding of return type
Code Examples
Using auto for type inference in various contexts.
cpp
1// Basic auto usage
2auto x = 42; // int
3auto y = 3.14; // double
4auto s = "Hello"s; // std::string (with literal suffix)
5
6// Auto with iterators (cleaner code)
7std::vector<int> vec = {1, 2, 3, 4, 5};
8for (auto it = vec.begin(); it != vec.end(); ++it) {
9 std::cout << *it << " ";
10}
11
12// Range-based for with auto
13for (const auto& val : vec) {
14 std::cout << val << " ";
15}
16
17// Auto with lambdas
18auto add = [](int a, int b) { return a + b; };
19
20// Return type deduction (C++14)
21auto multiply(int a, int b) {
22 return a * b; // Compiler deduces int
23}
24
25// decltype
26int a = 5;
27decltype(a) b = 10; // b is int