Using auto in loops c++

A range based loop could be a cleaner solution:

for (const auto& i : a)
{

}

Here, i is a const reference to an element of container a.

Otherwise, if you need the index, or if you don't want to loop over the entire range, you can get the type with decltype(a.size()).

for (decltype(a.size()) i = 0; i < a.size(); ++i) {
}

Trying to be const-correct whenever possible, I usually write:

const auto n(a.size());
for (auto i = decltype(n){0}; i < n; ++i)
{
}

It isn't very concise, but it's clear that you want a variable initialized to 0 of n's type (and n is const).


Depending on what you want to do inside the loop and the capabilities of your compiler, range-based for loop might be a better solution.

All of your presented solutions are not bad in most situations, with minor differences Your first solution is actually worse choice and that's exactly what your compiler tells you. Second solution is better but if you want to avoid directly defining types for simplicity or some future changes, you can do the following:

auto n = a.size();
for (decltype(n) i = 0; i < n; i++) {
}

This way you bind the i and n types to always match each other.


If you used the correct literal, you'd be fine: 0U. auto sees a literal of type int, so that is the type of i. Add the U and it will see an unsigned int literal instead. Otherwise, you'd want to make use of decltype as others suggested, especially since sizeof(size_t) may be greater than sizeof(int) (it is on Windows, OS X, etc. if running in 64-bit long mode).