Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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)

like image 783
adhanlon Avatar asked Nov 27 '09 06:11

adhanlon


4 Answers

You can do:

while (1) {
   //some code
   if ( condition) {
       break;
   }
   // some more code
}
like image 60
Sean McCauliff Avatar answered Oct 18 '22 19:10

Sean McCauliff


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);
like image 40
outis Avatar answered Oct 18 '22 18:10

outis


Well, I think you should move the condition to the middle of the loop(?):

while (true)
{
  ...
  // Insert at favorite position
  if (condition)
    break;
  ...
}
like image 23
Khaled Alshaya Avatar answered Oct 18 '22 19:10

Khaled Alshaya


Technically, yes:

 for ( ;CodeBefore, Condition; ) {CodeAfter}
like image 40
ima Avatar answered Oct 18 '22 19:10

ima