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?
If you do not make sure that
verticeshas at least one entry the subtractionvertices.size()-1could lead to underflow (i.e. a very large value from the subtractionsize_t(0)-1) and your loop could run much longer than you want.A more idiomatic solution would be to loop