[Solved] C++ for loop continue to loop even though it shouldn’t


It should be noted that I’m only guessing about what happens here…

My guess is that j becomes equal to j2 inside the loop, by one of the assignments. But then the increase j += inc happens and j is no longer equal to j2 when the loop condition is checked.


Generally speaking, a for loop is equivalent to a while loop:

for (a; b; c)
    d

is equivalent to

{
    a;
    while (b)
    {
        d;

        c;
    }
}

That means your first loop is equal to (with extra comments added)

{
    int j = j1;

    while (j != j2)
    {
        if(j < 0)
            j = curve2->controlPoints()->size()-1;
        if(j >= curve2->controlPoints()->size())
            j = 0;
        curve->addControlPoint(curve2->controlPoint(j)->pos(), curve2->controlPoint(j)->triangle());

        // At this point `j == j2`, so the loop condition is false

        // BUT then you do
        j += inc;

        // Here `j != j2` again, and the loop condition is true and will continue
    }
}

Perhaps your loop condition should be j - inc == j2 instead?

solved C++ for loop continue to loop even though it shouldn’t