c++variablestypeskeywordauto

How does the auto keyword deduct the type in C++


I wonder how the auto keyword determines the type of a variable in c++. I thought that statically typed languages couldn't do that. For example, how does this work:

#include <iostream>

int main()
{
    std::cout << "Hello World!\n";
    auto a = 5433245244524;
    std::cout << a << std::endl;
}

Solution

  • It works in same way as deduction of expression returning type for templates. It happens at compilation type, so it is a static type.

    Literal 5433245244524 comprises initializing expression. You can get the type of expression at compile time (static type) by using operator decltype(). E.g.

     decltype(5433245244524) a = 5433245244524;
    

    But autokeyword is more than that. It's a placeholder type. E.g. in statement

     const auto& a = 5433245244524;
    

    Here auto replaces identifier of type without qualifiers to form a compatible reference type.

    There is a number of other uses for keyword auto, e.g. function's trailing return type, etc. see https://en.cppreference.com/w/cpp/language/auto