-1

I'd like to use continue statement (parametrized) n times:

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

I'd like to use something like for(int i=0; i<n; ++i) continue; but the continue should be applied to the outer (while) loop. I'd like to skip n passes of the while loop.

The purpose is to always execute commandA, but skip n times commandB if running() condition is satisfied.

Is it possible to code that in C?

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 1
    What is the purpose to use `continue` in such way? – Edgar Rokjān Mar 06 '16 at 20:03
  • 2
    What does it mean to continue 7 times? Please show a more realistic example. – Oliver Charlesworth Mar 06 '16 at 20:03
  • It's not quite clear what you want to achieve. Do you want to skip the first seven passes through a `while` loop? (Or are you confused about what the `continue` statement does?) – M Oehm Mar 06 '16 at 20:05
  • Yes, I'd like to skip n passes of the while loop. I tried to narrow my problem, I could include other parts of my code but that is not relevant to the problem itself. – Jan Turoň Mar 06 '16 at 20:08
  • Then you could just appropriately modify whatever state is being used in the loop condition (e.g. if it's `while (i++ < N)`, then you should do something like `if (something) { i +=7; continue; }`.) – Oliver Charlesworth Mar 06 '16 at 20:10

3 Answers3

1

You could use an extra variable, like this, if I understood correctly what you are trying to achieve:

#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;
}

You short circuiting will come into play (as I explained here), which will protect max_skip from decreasing.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

One way would be:

int n = 7;
while(running()) {
  commandA;
  if (n) { --n; continue; }
  commandB;
  ...
}
M.M
  • 138,810
  • 21
  • 208
  • 365
0

continue can only be used to jump to the next iteration of the loop it appears in. You can't parametrize it, and you can't make it apply to any other loop. You will have to rewrite your loop.

Cecilio Pardo
  • 1,717
  • 10
  • 13