Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c or c++ can a loop have both "do" and "while" sections?

Given the common while() statement in both do ... while and while loops, and the way the place where a while loop's body would be replaced with a semicolon on a do ... while as if it's a compound statement being turned into an empty statement (or ending the line of a long statement):

Does the syntax in any of the C family languages allow for a "do while and while" loop with both bodies defined?

Presumably the semantics would be a single loop with some operations occurring before the check and some after.

For example:

do {
  foo();
} while ( baz() == true ){
  bar();
}

foo() would always occur once but bar() would only occur after if baz() returned true.

like image 975
davolfman Avatar asked Dec 15 '25 04:12

davolfman


2 Answers

They cannot be used at the same time. The syntax is either:

while ( expression ) statement

or:

do statement while ( expression ) ;

So you can't do this as in your example:

do {
  foo();
} while ( baz() == true ){
  bar();
}

But you can come close with this:

do {
  foo();
  if (!baz()) break;
  bar();
} while (1);
like image 124
dbush Avatar answered Dec 16 '25 18:12

dbush


You seem to be asking for

do
    statement0
while (condition)
    statement1

This can be accomplished with:

do
{
    statement0
    if (!(condition)) break;
    statement1
} while (1);
like image 26
Eric Postpischil Avatar answered Dec 16 '25 18:12

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!