继续n次迭代

时间:2016-03-06 20:01:22

标签: c loops

我想使用continue语句(参数化)n次:

int n = 7;
while(running()) {
  commandA;
  if(something) continue; // <- not once, but n times
  commandB;
  ...
}

我想使用for(int i=0; i<n; ++i) continue;之类的东西,但是应该将continue应用于外部(while)循环。我想跳过while循环的n次传递。

目的是始终执行commandA,但如果满足commandB条件,则跳过n次running()

是否可以在C中编码?

3 个答案:

答案 0 :(得分:1)

如果我理解你想要实现的目标,你可以使用额外的变量,这样:

#include <stdio.h>

int main(void) {

        int max_skip = 7;
        int i = 0;
        int something;
        while(i < 10) {
                something = i % 2;
                if(something && max_skip-- >= 0)
                        continue;
                ++i;
        }
        return 0;
}

短路将发挥作用(正如我解释here),这将保护max_skip不会减少。

答案 1 :(得分:1)

一种方法是:

int n = 7;
while(running()) {
  commandA;
  if (n) { --n; continue; }
  commandB;
  ...
}

答案 2 :(得分:0)

markSupported()只能用于跳转到它出现的循环的下一次迭代。你不能对它进行参数化,也不能让它适用于任何其他循环。你将不得不重写你的循环。