Home Item 1 - auto (English)
Post
Cancel

Item 1 - auto (English)

Auto

In C++11, automatic type inference (using the auto keyword) allows the compiler to deduce the type of a variable based on the type of the initialization expression. This makes the code more concise and easier to understand because, well, once the compiler knows what type it is, you don’t have to write it – it’s more in line with human nature (laziness). Actually, modern IDEs are already quite powerful; you can hover over variables to see their types. Writing out types all the time can actually hinder readability.

Let’s dive straight into the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>

int main() {
    // Example 1: Using auto to deduce integer type
    auto x = 5; // x is deduced as int type
    std::cout << "x: " << x << std::endl;

    // Example 2: Using auto to deduce floating-point type
    auto y = 3.14; // y is deduced as double type
    std::cout << "y: " << y << std::endl;

    // Example 3: Using auto to deduce complex types (such as STL containers)
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    for (auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

Execution Result

Desktop View

Usage:

  1. When the type of the initialization expression is long or complex, you can use auto to make the code more concise and clear.
  2. When the type is obvious and unlikely to change, using auto can improve the readability of the code.
  3. When using template programming or certain generic code, auto can help reduce errors from repeating type names and make the code more flexible.
  4. When dealing with complex iterator types or STL containers, auto can reduce errors and make the code more concise.

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍