capypad
0 day streak
cpp / beginner
Snippet

Type Inference with the auto Keyword

The auto keyword tells the compiler to automatically deduce the variable's type from its initializer. This reduces boilerplate when types are verbose, like standard library containers. The compiler knows that 25 is an int, 19.99 is a double, and "Charlie" is a std::string. Using auto improves code readability and reduces type errors.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <typeinfo>
 
int main() {
auto age = 25;
auto price = 19.99;
auto name = std::string("Charlie");
auto initial = 'A';
 
std::cout << "age is int: " << (typeid(age).name() == "i") << std::endl;
std::cout << "price is double: " << (typeid(price).name() == "d") << std::endl;
std::cout << "name is string: " << name << std::endl;
std::cout << "initial is char: " << initial << std::endl;
 
auto result = age + price;
std::cout << "result type inferred from expression" << std::endl;
 
return 0;
}
Breakdown
1
auto age = 25;
Compiler deduces int from integer literal 25
2
auto price = 19.99;
Compiler deduces double from floating-point literal
3
auto name = std::string("Charlie");
Compiler sees explicit std::string constructor call
4
auto initial = 'A';
Compiler deduces char from character literal
5
auto result = age + price;
Type is deduced from the result of expression (int + double = double)