Message-ID: <39E24E12.D870AB@cs.berkeley.edu>
Date: Mon, 09 Oct 2000 16:00:34 -0700
From: Ben Liblit <liblit@EECS.Berkeley.EDU>
Subject: Re: ick, ick -- grossness in linux kernel
> Anyone know why this code gets wrapped in a useless do loop?
Let me guess: the code you found came from a macro expansion, right?
This is a standard trick when you want a macro that expands into
multiple statements. Suppose I want a macro "AB(x)" that executes two
statements: a(x) followed by b(x).
Here's one approach that doesn't work:
#define AB(x) a(x); b(x);
if (p)
AB(z); /* oops! b(z) is outside of conditional */
Here's another approach that also doesn't work:
#define AB(x) { a(x); b(x); }
if (p)
AB(z);
else /* oops! extra semicolon before "else" */
foo();
Here's the approach that works:
#define AB(x) do { a(x); b(x); } while (0)
if (p)
AB(z);
else
foo();
It's an ugly trick, but a popular one just the same.
This archive was generated by hypermail 2b30 : 11/04/02 PST