auto
- C++ course
- Beginner
- Lesson 8/116
- 4 min
Learn to declare variables with auto where the compiler infers the type.
auto
The auto keyword lets the compiler deduce the variable type from its initial value. When you write auto x = 10;, x becomes int; auto y = 2.5; makes y a double.
This saves you from typing long type names: auto it = vec.begin(); and so on. You let the compiler figure out the type instead of spelling it out.
auto always requires an initial value; auto x; is invalid because the type cannot be deduced. Deduction happens at compile time with no runtime cost.
Limits of auto
auto is powerful but has limits you should know:
- An initial value is required:
auto x;is invalid - For references use
auto&:auto& r = x; constis not preserved:const int c = 5; auto a = c;here a isint, notconst int
For complex types, auto improves readability. But if the type becomes unclear, spelling it out is better. auto is used only for local variables; it cannot be used in function parameters (before C++20).
Practice Declare variables with auto
Inside main, declare four variables with auto: count with value 10, rate with 2.5, letter with 'Z', ok with true. Print each with std::cout using std::endl.
Starter code
#include <iostream>
int main() {
// Declare four variables with auto
// Print with std::cout
return 0;
}Sample solution
#include <iostream>
int main() {
// Declare four variables with auto
auto count = 10;
auto rate = 2.5;
auto letter = 'Z';
auto ok = true;
// Print with std::cout
std::cout << count << std::endl;
std::cout << rate << std::endl;
std::cout << letter << std::endl;
std::cout << ok << std::endl;
return 0;
}Expected output
10 2.5 Z 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match auto deductions
| Term | Meaning |
|---|---|
auto x = 10; |
int |
auto y = 2.5; |
double |
auto z = 'A'; |
char |
auto ok = true; |
bool |
2 What does auto do?
- It gives the memory address of the variable
- It deletes the variable
- It deduces the type from the initial value Correct answer
- It makes the variable constant
Explanation: auto deduces the type from the initial value.
3 Declaring with auto
____ count = 10;
auto count = 10;
Explanation: In auto count = 10; count becomes int.