【问题标题】:Does the number of iterations of the 'for' loop change if the second argument changes in one of the iterations?如果第二个参数在其中一次迭代中发生变化,“for”循环的迭代次数是否会发生变化?
【发布时间】:2021-09-29 02:25:50
【问题描述】:

我这里有这段代码:

for(i = openGates[0]; i < closeGates[0]; i++) {
    if(str[i] == '(') {
        closeGates.removeFirst();
        openGates.removeAt(1);        
    }
}

如果找到大括号,closeGates[0] 的值将会改变。会不会改变迭代次数?

【问题讨论】:

  • 会的。每次迭代都会评估所有变量。
  • 你可以编写一个 10 行的程序来测试它。
  • @drescherjm 是的,我可以,但我没有简单的 IDE rn
  • 你可以试试网上的,比如:ideone.com
  • @Pere_Strelka 有很多在线编译器可供您使用:ideone.com、godbolt.org、onlinegdb.com、coliru.stacked-crooked.com 等等。

标签: c++


【解决方案1】:

是的,iteration-expression 在每次循环迭代后执行。 此答案的参考: https://en.cppreference.com/w/cpp/language/for

【讨论】:

    【解决方案2】:

    显然,没有人决定回答,我想结束这个问题:是的,在 C++ 中,'for' 循环在每次迭代之前评估其条件,因此迭代次数可能会改变。

    【讨论】:

    • 实际上,for 语句的 condition 部分在循环的每次迭代之前进行评估。
    • @AdrianMole 好吧,你是对的,技术上我也是,但固定
    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多