Forgot do in do... while loop

thedoctar
:

I had an annoying bug, where I forgot to write do in a do ... while loop.

int main() {
  int status=1;
  /*do*/ {
    status = foo();
  } while (status);
}

Why does this still compile and run? It seems to me that the compiler should reject this as nonsensical or at least raise a warning (I have -Wall in my compiler options). I'm using C++11.

From what I could tell, the braced code runs { ... } and then the programme checks the condition in the while clause ad infinitum.

CherryDT
:

I'm assuming you actually had int status outside of the loop body, otherwise the code wouldn't compile. (Not even with the do in place.)

With that fixed, the code you wrote is still valid without do, but does something differrent, as you already correctly noted. Let me rewrite it slightly to show how it is interpreted:

int main () {
  int status;

  { // anonymous braced block that just creates a new scope
    status = foo();
  }

  while (status) {
    // empty loop body
  }
}

A stand-alone block like that does have its uses, for example to utilize RAII - it could contain a local variable with an object whose destructor frees some resource when it goes out of scope (for example a file handle), among other things.

The reason that the while (status); is the same as while (status) {} is because you are allowed to put either a single statement or a block, and ; is a valid statement that does nothing.

And writing something like while (someVariable); isn't even nonsensical in general (although of course in this case it is) because it is essentially a spinlock, a form of busy waiting - it would leave the loop if another processor core, some I/O component or an interrupt would modify the value of someVariable so that the condition is no longer fulfilled, and it would do so without any delay. You would probably not write such code on a desktop platform where "hogging CPU" is a bad thing (except in specific scenarios in kernel-mode code), but on an embedded device like a microcontroller (where your code is the only code that runs) it can be a perfectly valid way of implementing code that waits for some external change. As pointed out by Acorn in the comments, this would of course only make sense if someVariable were volatile (or otherwise non-predictable), but I'm talking about busy loops on a variable in general.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related