Search code examples
c++c++11auto

is auto type detection only looking at one statement


For the two for loop below, are they equivalent? Basically does the auto look over "=0" assignment and see iter is compared with s.size() and so decides iter is of type decltype(s.size())?

string s;
for(auto iter=0; iter<s.size();iter++)

string s;
for(decltype(s.size()) iter=0; iter<s.size();iter++)


Solution

  • and see iter is compared with s.size() and so decides iter is of type decltype(s.size())?

    No. auto only deduces type from the initializer, given auto iter=0;, the type is deduced from 0 then it'll be int.

    in the type specifier of a variable: auto x = expr;. The type is deduced from the initializer.

    And you can specify the type with auto like:

    auto iter = 0u;  // unsigned int
    auto iter = 0ul; // unsigned long int
    auto iter = 0uz; // std::size_t, since C++23
    

    BTW in decltype(s.size()) iter=0;, the type would be deduced from s.size() based on the rule of decltype, it won't be influenced by the fact that iter is compared with s.size() later either.