The auto
keyword in C++ is used for type deduction. When you use auto
, the compiler infers the type of the variable from its initializer. This can be convenient and can make your code more readable in certain situations:
Example 1: When the type is long or complicated, especially when using templates:
std::map<std::string,
std::vector<int>> my_map{GetMap()};
// vs
auto my_map{GetMap()};
Example 2: When the exact type isn't important for understanding the code:
// If we only care that result is,
// say, a number, auto is fine
auto result = some_complex_function();
Example 3: With iterators, where the exact type can be verbose:
for (std::vector<int>::const_iterator it =
vec.begin(); it != vec.end(); ++it) {
// ...
}
// vs
for (auto it = vec.begin();
it != vec.end(); ++it) {
// ...
}
However, there are also situations where using auto
can make your code less readable or even cause bugs:
Example 1: When the type is not immediately clear from the context:
// Is this an int? A long?
// Unclear without more context.
auto x = 5;
Example 2: When you need to be explicit about type conversions:
// The cast is hidden
auto result = static_cast<int>(some_float);
Example 3: When you want to commit to a specific type:
// i is an int
auto i = 5;
// j is a long, which might not be what you want
auto j = 5L;
As a rule of thumb, use auto
when it makes your code more readable by avoiding long type names or when the exact type isn't important. But prefer explicit types when the type is not immediately clear, when type conversions are involved, or when you want to commit to a specific type.
Answers to questions are automatically generated and may not have been reviewed.
Learn the fundamentals of C++ programming: declaring variables, using built-in data types, and performing operations with operators