is auto type detection only looking at one statement

Viewed 76

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++)

3 Answers

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.

Nope. Whenever a variable declaration has a "placeholder type" (auto, decltype(auto), const auto&, etc.), only that variable's initializer is used to deduce the actual type.

So in the first snippet, the type of iter is decltype(0) is int.

No, the loops are not equivalent. auto deduces the type only from the initializer. In your loop, that's 0 and 0 has the type int. So your first loop is

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

while the second loop is

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

where conatiner_size_type is most likely a std::size_t


Depending on what you are doing, you may want to use a ranged based for loop like

for(auto character : s)
    // loop logic
    

and this will loop through the string and character will be the character at the current position in the string the loop is at.

Related