C ++ for循环即使不应该继续循环

时间:2019-03-08 12:52:12

标签: c++ qt

        int inc = swap ? 1 : -1;
        for(int j=j1; j!=j2; j+=inc){
            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());
        }

我发现在某些情况下,此for循环无限。使用调试器查看时,j确实达到了j2,但由于某种原因继续循环。

然后我尝试在循环中如果j == j2添加一个中断(从技术上讲是j-inc,因为j再次进入循环时会递增)

    for(int j=j1; j!=j2; j+=inc){
            if (j - inc == j2)
            {
                qDebug() << "break =================================";
                break;
            }
            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());
        }

这样做确实解决了问题(并且确实显示了“中断”),但这真的没有任何意义吗? 为什么第一个for循环会以这种方式起作用?

编辑: 我正在遍历列表的一部分(在值j1和2之间)。取决于交换参数(布尔值),迭代可以同时进行。如果j到达列表的末尾之一,则在另一侧继续(例如,如果j1 = 5,j2 = 1且列表大小为7,则j将采用以下值:5 6 0 1)

1 个答案:

答案 0 :(得分:4)

应该注意,我只是 猜测 这里发生的事情...

我的猜测是,通过其中一项分配,j在循环内等于j2。但是随后会出现j += inc的增加,并且在检查循环条件时j不再等于j2


通常来说,for循环等效于while循环:

for (a; b; c)
    d

等同于

{
    a;
    while (b)
    {
        d;

        c;
    }
}

这意味着您的第一个循环等于(添加了额外的注释)

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

也许您的循环条件应该改为j - inc == j2