cpp / beginner
Snippet
The Auto Keyword: Automatic Type Deduction
The 'auto' keyword tells the compiler to automatically deduce the variable's type from its initializer. This reduces verbosity and is especially useful for complex types like iterators or lambda expressions. The compiler determines the type at compile time - there is no runtime performance cost. auto is required when working with iterators and lambda functions, and makes code more maintainable when types might change.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>#include <vector>#include <typeinfo>int main() {auto number = 42;auto decimal = 3.14;auto letter = 'A';auto word = std::string("Hello");std::cout << "number: " << number << " (type: " << typeid(number).name() << ")" << std::endl;std::cout << "decimal: " << decimal << " (type: " << typeid(decimal).name() << ")" << std::endl;std::cout << "letter: " << letter << " (type: " << typeid(letter).name() << ")" << std::endl;std::vector<int> numbers = {1, 2, 3, 4, 5};for (auto it = numbers.begin(); it != numbers.end(); ++it) {std::cout << *it << " ";}std::cout << std::endl;auto sum = [](int a, int b) { return a + b; };std::cout << "Sum: " << sum(5, 3) << std::endl;return 0;}
Breakdown
1
auto number = 42;
Compiler deduces int type from the integer literal 42
2
auto decimal = 3.14;
Compiler deduces double type from the floating-point literal
3
auto word = std::string("Hello");
Compiler deduces std::string type from the string literal
4
for (auto it = numbers.begin(); ...
auto simplifies iterator declaration for containers
5
auto sum = [](int a, int b) { return a + b; };
auto captures the lambda function type automatically