views:

2269

answers:

2

How do you Make A Repeat-Until Loop in C++? As opposed to a standard While or For loop. I need to check the condition at the end of each iteration, rather than at the beginning.

+12  A: 
do
{
  //  whatever
} while ( !condition );
Adrien
Uhh ... This is pretty sad. Emil hit submit sooner than I did ... The "accepted" should go to him ...
Adrien
You have less rep, and it's an extremely simple question, so I'll gladly give it to you. :)
Emil H
As jalf said, though: If you want an do until loop rather than a do while loop you'll have to negate the condition.
Emil H
Thanks. :) It sill feels unfair, though.
Adrien
Thanks a ton for your help, you guys! SO is the best!
Clarified the example slightly ...
Adrien
The code in the answer doesn't look like C++ code. Only if `null` is an instance of type `Planet`.
Kirill V. Lyadvinsky
Sorry, I was more interested in getting the point across than in showing perfect C++ code. Happy now?
Adrien
If you really wanted to, you could do `#define repeat do` and `#define until(cond) while(!(cond))`, but anyone who resorts to that kind of preprocessor abuse should be shot.
Adam Rosenfield
#define true false and #define false true have always been among my favorites.
Adrien
Please, do not use defines(even as a joke). Use template functions.@Adrien, your code is better now, but `condition` still undefined ;)~~~
Kirill V. Lyadvinsky
+3  A: 

When you want to check the condition at the beginning of the loop, simply negate the condition on a standard while loop:

while(!cond) { ... }

If you need it at the end, use a do ... while loop and negate the condition:

do { ... } while(!cond);
Zifre