搜尋此網誌

2025年3月4日星期二

auto in C++

In C++, the auto keyword is used for type inference, meaning the compiler will automatically deduce the type of the variable from its initializer. When you use auto* p, it declares a pointer p with the type inferred from the initializer. Here's an example:

#include <iostream>


int main() {

    int x = 42;

    auto* p = &x;  // p is deduced to be an int*


    std::cout << "Value of x: " << x << std::endl;  // Output: 42

    std::cout << "Value of p: " << *p << std::endl; // Output: 42


    return 0;

}


In this example:

int x = 42; initializes an integer variable x.

auto* p = &x; declares a pointer p and initializes it with the address of x. The type of p is deduced to be int*.

Using auto can make your code cleaner and easier to read by removing the need to explicitly state the type, especially in cases where the type is complex or verbose.

Microsoft Copilot

deduce: to form an opinion about something based on the information or evidence that is available

explicitly: clearly or directly, so that the meaning is easy to understand

verbose: using or containing more words than are needed

www.oxfordlearnersdictionaries.com

沒有留言:

發佈留言