What are the benefits and risks of using auto?
Short answer
Benefits: less verbose code, fewer explicit type mismatches, easier refactoring, and readable handling of complex types (iterators, lambdas). Risks: reduced readability if the deduced type is unclear, accidental copies (auto vs auto&), and unexpected types from expressions.
Advertisement
AModel answer
Benefits: less verbose code, fewer explicit type mismatches, easier refactoring, and readable handling of complex types (iterators, lambdas). Risks: reduced readability if the deduced type is unclear, accidental copies (auto vs auto&), and unexpected types from expressions. Use auto where the type is obvious or unwieldy, and be explicit when clarity or exact type matters.
auto total = items.size(); // std::size_t, not intReal-world example
Overusing auto in an API makes types hard to read; using it for local iterators improves clarity.
Likely follow-ups
- When can auto hurt readability? | What accidental copies can it cause?
Related topics