Table of Contents
The auto keyword allows the compiler to determine the data type of a variable from its initializer. This reduces the need to specify the type explicitly and helps simplify declarations.
This example demonstrates how auto deduces the type of different variables during compilation.
Source Code #
#include <iostream>
int main()
{
auto age = 21;
auto salary = 55000.75;
auto grade = 'A';
std::cout << "Age: " << age << '\n';
std::cout << "Salary: " << salary << '\n';
std::cout << "Grade: " << grade << '\n';
return 0;
}
Output #
Age: 21
Salary: 55000.8
Grade: A
Explanation #
auto age = 21;declaresageand deduces its type asintbecause the initializer is an integer literal.auto salary = 55000.75;deduces the type asdoublesince floating-point literals are of typedoubleby default.auto grade = 'A';deduces the type ascharbecause the initializer is a character literal.- The type deduction performed by
autooccurs during compilation. After deduction, the variable has a fixed type and behaves like any other variable of that type. - An
autovariable must be initialized when it is declared because the compiler requires the initializer to determine its type. std::coutprints the values stored in the variables without requiring knowledge of their explicitly written types.return 0;terminates the program successfully.