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 lo开发者_运维百科nger 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}
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.
A variation on Dahl's loop that does not involve a goto into the middle of a do-while() is to use a switch-default:
switch (0) do {
// some more code
default:
// some code
} while (expression);
精彩评论