1

Lately, I see more and more code pieces that use the template of:

do {
    ... some code ...
} while (false);

Why to do this? If I'm not mistaken, the code will run only one time so the loop is seem not to be needed.

My main encounters with this style were in Windows drivers, and low-level operations in some APIs.

Reflection
  • 1,936
  • 3
  • 21
  • 39

3 Answers3

8

It is sometimes used for implementing "structured goto". Inside such do-while region break and continue statements will pass control to the end of the region and continue execution of the code that follows such "cycle".

Another use, already mentioned in the comments, is to work as a compound statement envelope inside macros. The unique feature of do-while is that it requires a ; at the end. This allows it to work as a compound statement envelope that will "consume" the following ;. That feature allows one to write function-like macros with allow the caller to safely place a ; after them (see here: What does "do { ... } while (0)" do exactly in kernel code?)

Community
  • 1
  • 1
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • Cool. Any other reason? – Reflection Dec 17 '14 at 22:34
  • @Reflection: I doubt there are any. – AnT stands with Russia Dec 17 '14 at 22:42
  • I second this. This is the convention I always use for expanding function-like macros to keep the semi colon from being swallowed. See this example: https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_3.html#SEC29 Here another SO post: http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros – Nick Dec 17 '14 at 22:44
1

One example od such thing is to have conditinal break inside this "loop". You can stop executing the rest of code - some sofisticated way to avoid infamous "goto".

Kuba
  • 839
  • 7
  • 16
1

It is a flow control style that allows for skipping all the remaining code in the code block of the do { code block } while( false );. Very useful when you want to stop processing the remaining code in the code block, but still perform the rest of the code after the while(false);. This is a common pattern allowing a function to clean up after an error, for instance.

So in other words: it is a way to "hide" goto functionality.

StarPilot
  • 2,246
  • 1
  • 16
  • 18