Do if(){ } while() statement

Three Diag picture Three Diag · Jul 29, 2015 · Viewed 7.7k times · Source

I am currently working on somebody's else code, with a statement like this

if(x.start()) do if(y.foo(x)) {

// Do things

}while(x.inc())

here x is custom class that holds information on y and allows iteration through its element in a special order. I put this info if relevant, but my question is more general:

I thought that in a do{}while() statement the do part had to be followed by the bracket, and this togheter with the while() condition at the end defines the do-while loop.

  • Why can we put an if right after the do?
  • What does it do?
  • What else can be put in between do and {?

I couldn't find other questions relating to this or on google, most stuff related to putting if statements inside while loop.

Answer

T.C. picture T.C. · Jul 29, 2015

The grammar permits any statement between do and while. It's just you usually see a particular form of statement there - the compound-statement, { /* statements */ }, also commonly called a block.

The do-while portion of the code is exactly equivalent to

do {
    if(y.foo(x)) {
        // Do things
    }
} while(x.inc());