On Wed, Sep 07, 2016 at 09:10:09AM -0500, Derek Martin wrote:
> Like I said, I'm familiar with the do {} while (0) construct, but I
> could swear I ran into an odd case where it caused some sort of
> problem...  

There are several possibilities here.  There are probably others, but
I can think of two:

Since it's a while loop, it may interfere with continue/break.  This
is mostly an issue when the macro is intended to be able to take a
block of code as its argument... which I'll agree is rare and should
be avoided (though as I said, I feel that way about macros in
general).

Another case is where you actually want the do {} while structure, but
you want the while to be terminated by a macro argument.  A simple
example:

#define FOO(A, I) do { my_func((A), (I)) } while ((I))

int main(...)
{
    int i = 99;
    FOO("blah", --i);
    return 0;
}

In this case, the decrement operator is meant to terminate the loop
by eventually decrementing i to 0.  The trouble is, it's evaluated
twice on each iteration, so the loop will never terminate, since it
starts on an odd value and the pre-decrement operator was used.
Regardless of whether it terminates, it'll most probably produce
undesired results, though more because the argument is evaluated twice
than because of the do/while per se.

The lesson is, macros suck.  Period. ;-)  If you want your macro to
always give the expected result, abandon the macro entirely and write
a function instead.

-- 
Derek D. Martin    http://www.pizzashack.org/   GPG Key ID: 0xDFBEAD02
-=-=-=-=-
This message is posted from an invalid address.  Replying to it will result in
undeliverable mail due to spam prevention.  Sorry for the inconvenience.

Attachment: pgppJWM2FqzUw.pgp
Description: PGP signature

Reply via email to