I want to have a while loop do something like the following, but is this possible in c++? If so, how does the syntax go?
do {
//some code
while( expression to be evaluated );
// some more code
}
I would want the loop to be exited as soon as the while statement decides the expression is no longer true( i.e. if expression is false, //some more code is not executed)
You can do:
while (1) {
//some code
if ( condition) {
break;
}
// some more code
}
A little background and analysis: what you're asking for I've heard called a "Dahl loop", named after Ole-Johan Dahl of Simula fame. As Sean E. states, C++ doesn't have them (ima's answer aside), though a few other languages do (notably, Ada). It can take the place of "do-while" and "while-do" loops, which makes it a useful construct. The more general case allows for an arbitrary number of tests. While C++ doesn't have special syntax for Dahl loops, Sean McCauliff and AraK's answers are completely equivalent to them. The "while (true)" loop should be turned into a simple jump by the compiler, so the compiled version is completely indistinguishable from a compiled version of a hypothetical Dahl loop. If you find it more readable, you could also use a
do {
...
} while (true);
Well, I think you should move the condition to the middle of the loop(?):
while (true)
{
...
// Insert at favorite position
if (condition)
break;
...
}
Technically, yes:
for ( ;CodeBefore, Condition; ) {CodeAfter}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With