R
Richard Bos
|
| [This shoudl be a FAQ but I can't currently check since the C FAQ site
| appears to be down.]
It is. 10.4 in the text version on my computer.
|> Having this code:
|> do {
|> if (flag_prg)
|> printf("%-" PROGNAME_WIDTHs "s"," " PROGNAME_BANNER);
|> } while (0)
|>
|> why the use of while?
|
| As you present it, none. In fact it's a syntax error since there is
| no ; after the while (0). This is a big clue that the code comes
| from a macro.
|
| The purpose of the loop is syntactic. It encloses the 'if' in a
| statement (when the ; is added by the macro invocation) so that no
| surprises happen to the users of the macro. Consider the simpler:
|
| #define PRINT_BANNER if (flag_prg) \
| printf("%-" PROGNAME_WIDTHs "s"," " PROGNAME_BANNER)
|
| and a usage like this:
|
| if (first_run)
| PRINT_BANNER;
| else puts("Going again...";
|
| The 'else' will be taken to be part of the inner if regardless of the
| indentation. do {} while (0) gets round this and other potentials
| problems with macros that expand to statements.
Do you have an example where enclosing in plain { } is not good enough?
Yes: the one above. If you wrote
#define PRINT_BANNER { statements... }
then
if (first_run)
PRINT_BANNER;
else
puts("Going again...");
would result in
if (first_run)
{ statements... };
else
puts("Going again...");
which, because of the extra semicolon, is a syntax error.
If, OTOH, you write
#define PRINT_BANNER do { statements... } while (0)
then
PRINT_BANNER;
is a single, valid statement, which will run once and only once, in any
context where a normal single-line statement would have done so -
including the above if-else statement (try it!).
Richard