C++ - back to start of loop without checking the condition

1.2k views Asked by At

Programming on perl, we can use a smart function named 'redo' - we can go back to the start of the loop, without looking at the condition. It's useful when, for example, we create a table in which we must to set a expected values/characters (e.g. "a-b-c", nothing else). I would like to ask if exist in C++ function like that. I would be grateful for your help.

4

There are 4 answers

1
Michael Anderson On BEST ANSWER

There is no redo keyword for going back to the start of a loop, but there's no reason you couldn't do it with goto. (Oh I feel so dirty recommending goto...)

int tries = 0;
for(int i=0; i<10; ++i) {
  loop_start:
  bool ok = ((i+tries)%3==0);
  if(ok) {
     ++tries;
     goto loop_start;
  }
}
0
john zhao On

I think a more reasonable solution is

int trie=0;
for(int i=0; i<10; i++) {
    while((i+tries)%3==0 {
         ++tries;
    }
}
0
mpapec On

If you want to avoid goto at any cost,

int tries = 0;
for (int i=0; i<10; ++i) {do{

  bool redo = ((i+tries)%3 == 0);

  if (redo) { ++tries; }
  else      { break; }

} while(1); }
0
Walter On

Why can you not use a simple while loop?

auto is_okay = [](char x) { return x=='a' || x=='b'; };
container C;
for(std::size_t i=0; i!=C.size(); ++i) {
  char x;
  while(!is_okay(x=obtain_new_character()));  // get new x until it's okay
  C[i]=x;
}

Or, equivalently, a do while loop

container C;
for(std::size_t i=0; i!=C.size(); ++i) {
  char x;
  do {
    x=obtain_new_character();
  } while(x!='a' && x!='b');
  C[i]=x;
}

Or even a for loop

container C;
for(std::size_t i=0; i!=C.size(); ++i) {
  char x=0;
  for(; x!='a' && a!='b'; x=obtain_new_character());
  C[i]=x;
}