cpp / beginner
Snippet
Type Inference with auto
The auto keyword tells the compiler to deduce the variable's type from its initializer. This reduces verbosity and works especially well with complex types like iterators. The actual type is determined at compile time, so there's no runtime performance cost. It's particularly useful for long type names and iterator declarations.
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
26
#include <iostream>#include <vector>#include <string>int main() {auto age = 25;auto name = std::string("Lisa");auto price = 19.99;std::cout << "Age: " << age << " (type matches int)" << std::endl;std::cout << "Name: " << name << " (type matches std::string)" << std::endl;std::cout << "Price: " << price << " (type matches double)" << std::endl;std::vector<int> numbers = {10, 20, 30, 40, 50};for (auto it = numbers.begin(); it != numbers.end(); ++it) {std::cout << *it << " ";}std::cout << std::endl;auto calculate = [](int a, int b) -> int {return a + b * 2;};std::cout << "Lambda result: " << calculate(3, 4) << std::endl;return 0;}
Breakdown
1
auto age = 25;
The compiler sees the literal 25 and deduces the type should be int automatically
2
auto name = std::string("Lisa");
The explicit constructor call tells auto to infer std::string as the type for name
3
auto it = numbers.begin()
Creates an iterator variable without writing the verbose std::vector<int>::iterator type
4
auto calculate = [](int a, int b) -> int
Uses auto for a lambda function's type, which would be very complex to write out explicitly