I came across this piece of code for an LPCxxxx microcontroller, in the reset routine.

do {
    const uint32_t topOfStack = (uint32_t) &_vStackTop;
} while(0);

I was wondering why this is inside a do-while loop (which executes only once) instead of writing those instructions in a straight-forward way (by which I mean outside the loop)


In this particular case, not covered in the Stackoverflow answers, it gives you the opportunity to declare a local variable that is shared among the three statements and used nowhere else.

This kind of explicit optimization of storage can be important on small microcontrollers.

|improve this answer|||||
  • 3
    \$\begingroup\$ The curly braces alone would do that, without the do and the while(0);. \$\endgroup\$ – Pete Becker Aug 20 '16 at 12:37
  • \$\begingroup\$ @PeteBecker: were these available in early C dialects too? \$\endgroup\$ – PlasmaHH Aug 20 '16 at 13:51
  • 3
    \$\begingroup\$ @PlasmaHH - I haven't looked, but as far as I know C has always been block scoped. \$\endgroup\$ – Pete Becker Aug 20 '16 at 14:03
  • \$\begingroup\$ Prior to the wonders of ANSI C, whether the block scope would achieve this was implementation dependent. I seem to recall that the very early Lattice C would not - it promoted the variable to function scope. \$\endgroup\$ – Peter Smith Aug 20 '16 at 17:01
  • 2
    \$\begingroup\$ Note that I countered the downvote because this method is guaranteed to achieve the requirement (as stated by Dave Tweed) even when the compiler may not be ANSI compliant (the state of play for many years). \$\endgroup\$ – Peter Smith Aug 20 '16 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.