Coding: Block Delimiters

By this, I mean things like { and } in C and C++, BEGIN and END in Pascal, etc.

Delimiters should always go on a line by themselves, one each. There is one exception: in C (and thus C++, and also any languages with a similar construct with delimiters), the one that ends a "do-while" loop (not a plain "while" loop!) may (in fact should) be followed by the while-statement. This will diminish confusion between the end of a "do-while" loop and a bodiless normal "while" loop, since the latter will be at the start of a line. (Note that some languages have similar constructs that do not require such delimiters, such as the REPEAT-UNTIL loops in Pascal.)

Whether or not to indent delimiters past the controlling conditional, is a personal choice. Personally, I think it's fugly, but many people do it, especially those influenced by Charles Petzold (of Windows programming books fame). Whichever you do, be consistent!

For examples:

  /* BAD, even though Kernighan & Ritchie do it! */
  while (foo == bar) {
    baz();
  }

  /* TOLERABLE */
  while (foo == bar)
    {
    baz();
    }

  /* GOOD! */
  while (foo == bar)
  {
    baz();
  }

  /* CONFUSING! */
  /* (The "while" part could look like a bodiless loop itself.) */
  do
  {
    baz();
  }
  while (foo == bar);

  /* CLEARER! */
  do
  {
    baz();
  } while (foo == bar);

In certain circumstances, macros that help build a single statement, by beginning and ending it, may be treated as delimiters. For example, at one place I worked, debugging traces were often done with macros such as:

#define LOGIF(x) { if (debugLevel >= x) printf (
#define LOGEND ); }
so that a statement like
  { if (debugLevel >= 5) printf ("length = %d\n", len); }
would be expressed as
  LOGIF(5) "length = %d\n", len LOGEND
(The LOGEND macro is so that the original source code braces don't get unbalanced.) A more complicated debugging output could be written as:
  LOGIF(5)
    "piece #%d, ID=%d, length = %d, width=%d, height=%d\n",
    pieceNum,
    piecePtr->id,
    piecePtr->len,
    piecePtr->wid,
    piecePtr->ht
  LOGEND