cpp / beginner
Snippet
Auto Keyword: Automatic Type Detection
The auto keyword tells the compiler to deduce the variable's type from its initializer. This reduces verbosity and often produces cleaner code. The compiler determines the type based on what value you assign. Use auto when the type is obvious or complex.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>#include <typeinfo>int main() {auto number = 42;auto decimal = 3.14;auto letter = 'A';auto text = "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::cout << "text: " << text << " type: " << typeid(text).name() << std::endl;return 0;}
Breakdown
1
auto number = 42;
Compiler deduces int type from integer literal
2
auto decimal = 3.14;
Compiler deduces double type from decimal literal
3
typeid(variable).name()
Shows the compiler's internal type name