Is it possible to have a while loop in c++ that makes the check in the middle of the loop instead of the beginning or end?

StackOverflow https://stackoverflow.com/questions/1807110

Question

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)

Was it helpful?

Solution

You can do:

while (1) {
   //some code
   if ( condition) {
       break;
   }
   // some more code
}

OTHER TIPS

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}

The answer is no, you can't have your loop automatically terminate when the condition that the while statement is supposed to evaluate is true until it actually evaluates it at the top (or bottom) of the loop. The while statement can't be placed in the middle of the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top