What is the usage of auto in C++?

In C++11, the ‘auto’ keyword was introduced for automatically inferring the type of a variable. Its syntax form is ‘auto variable_name = expression;’, where the type of the expression will be automatically deduced as the type of the variable.

The use of auto can simplify the code, eliminating the need for repeatedly declaring variable types and handling complex type inference situations, such as iterating through elements in a container using iterators or situations where the return type of a function is uncertain.

Here are some sample codes to demonstrate the usage of ‘auto’:

// 使用auto进行变量类型推导
auto num = 10; // 推导为int类型
auto name = "Alice"; // 推导为const char*类型
auto result = 3.14 + 2; // 推导为double类型

// 使用auto遍历容器中的元素
std::vector<int> numbers = {1, 2, 3, 4, 5};
for(auto it = numbers.begin(); it != numbers.end(); ++it) {
    std::cout << *it << " ";
}
// 输出:1 2 3 4 5

// 使用auto推导函数返回值类型
auto add(int a, int b) -> int {
    return a + b;
}
auto divide(double a, double b) -> decltype(a / b) {
    return a / b;
}

It is important to note that ‘auto’ can only be used when defining variables, and not in function parameters or class member variables. When using ‘auto’ to deduce the variable type, make sure that the expression’s type is clear, otherwise the compiler will not be able to deduce the correct type.

bannerAds