liveBook · Manning

Do statement

As explained in Modern C

A do-while loop is a C iteration construct that executes its dependent statement before testing whether its condition remains true.

A do statement repeats a dependent statement or block while a condition remains true. Unlike while, it executes that body before testing the condition, so the first iteration is unconditional. section 3.0 section 3.2

   while (condition) statement-or-block
   do statement-or-block while(condition);


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":8}],[{\"line\":1,\"ch\":25},{\"line\":1,\"ch\":30}],[{\"line\":0,\"ch\":31},{\"line\":0,\"ch\":33}],[{\"line\":1,\"ch\":16},{\"line\":1,\"ch\":18}],[{\"line\":1,\"ch\":3},{\"line\":1,\"ch\":5}],[{\"line\":0,\"ch\":31},{\"line\":0,\"ch\":33}],[{\"line\":1,\"ch\":16},{\"line\":1,\"ch\":18}],[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":8}],[{\"line\":1,\"ch\":25},{\"line\":1,\"ch\":30}]]"}
!@%STYLE%@!

The essential syntax places the condition after the body: do statement-or-block while (condition); The trailing semicolon is part of the do statement. section 3.2

Rewriting an iterative approximation

A Heron approximation can use a while loop when the condition is tested before each iteration. The do form moves the update first: do { x *= (2.0 - a*x); } while (fabs(1.0 - a*x) >= eps); Here, the approximation update runs once, then the product is tested to determine whether another iteration is needed. This expresses a process that must perform an update before checking whether it is close enough. section 3.2

TAKEAWAY

  • Choose do when the body must run before its continuation condition is evaluated; choose while when the condition should be checked first. section 3.2
  • Treat do as one of C’s three iteration statements alongside for and while; for remains the preferred form for domain iterations. section 3.4

How Modern C covers it

How deep it goes
Defines syntax, contrasts do with while, and demonstrates a numerical rewrite without developing implementation internals.
Examples
Demonstrates do by rewriting Heron’s approximation for computing multiplicative inverses.
What it assumes
Assumes familiarity with conditions and basic iteration, while distinguishing do from previously encountered for and while forms.
What you can do after
Apply via C syntax to place a continuation test after an iteration body.
How it connects
Connects do with for, while, conditions, and break as alternative or supporting control-flow constructs.

Also explained in

Compare how 2 books explain do statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.