Why is this loop infinite?
Question
I have some code for drawing polygons edges that is supposed to draw, for example, in a triangle with vertices 0, 1, and 2, the edges (0, 1), (1, 2), and (2, 0). I thought I could accomplish this like so:
for(size_t j = 0, k = 1; j <= vertices.size()-1; j++, k++){
if(j == vertices.size()-1){k = 0;} //For j to k final edge
...
//draw edges, etc.
...
}
...But this makes the k value explode into an infinite loop. I have looked this over and suspect that the problem could be in my indexing here, but if everything depends on j, I would think that maybe vertices.size() is messed up. Am I missing something in this code, or should I look more closely at the actual vertices vector?
Solution
If you do not make sure that vertices
has at least one entry the subtraction vertices.size()-1
could lead to underflow (i.e. a very large value from the subtraction size_t(0)-1
) and your loop could run much longer than you want.
A more idiomatic solution would be to loop
for (size_t j = 0, k = 1; j < vertices.size(); j++, k++) {
if ( j == vertices.size()-1) { //works, vertices has at least one entry
k = 0;
}
...
//draw edges, etc.
...
}
OTHER TIPS
You don't need to count over k :
size_t const count = vertrices.size()
for(size_t j = 0; j < count; j++) {
size_t k = (j + 1) % count;
// draw
}
This way k
is j+1
except when j is the max, in that case it's 0.
If vector "vertices" is empty, the loop will be approximately infinite. You are using unsigned integer arithmetic in the condition, so -1 will be 0xFFFFFFF or larger.
It wont be infinite loop if everything other than you gave here is correct. So best answer is check your other parts of code carefully.