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.
C++ - back to start of loop without checking the condition
1.2k views Asked by Plusce At
4
There are 4 answers
0
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;
}
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 recommendinggoto
...)