Using auto in loops c++

user2381422 picture user2381422 · Jul 6, 2013 · Viewed 20k times · Source

I get warning signed/unsigned mismatch for the following code:

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

The problem is that by assigning 0 to i it becomes int rather than size_t. So what is better:

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

or this:

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

or maybe you have a better solution? I like the first one more because it is bit more consistent, it just uses size_t rather than both size_t and auto for the same purpose.

Answer

juanchopanza picture juanchopanza · Jul 6, 2013

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) {
}