Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ for loop: evaluation of condition

I have got a (stupid?) C / C++ question about a loop:

for (size_t i = 0; i < std::distance(begin, end); ++i) {
  a.push_back(i);
}

begin and end are two iterator. My question is, is std::distance(begin, end) calculated for each element in the loop? Or is it better to use this version:

size_t dist = std::distance(begin, end);
for (size_t i = 0; i < dist; ++i) {
  a.push_back(i);
}
like image 915
martinus Avatar asked Dec 09 '22 05:12

martinus


2 Answers

Second version is better. In the first one the condition is evaluated each time (no automatic asumption about the result being invariant).

like image 54
cma Avatar answered Dec 11 '22 17:12

cma


Yes. The second version is better.

As for the first version, if the container type a is std::vector, and begin and end are iterators of a, then the push_back operation might cause resizing the vector, which in turn will invalidate begin and end iterators, and using them to calculate the distance in the next iteration will invoke undefined behaviour. In this case, the second is not only better, it is well-defined as well.

like image 24
Nawaz Avatar answered Dec 11 '22 18:12

Nawaz