Not compiling your code snippets considered harmful

Paul Wayper takes issue with the habbit kernel programmers have of #defining things as do { stuff; } while (0).

He points out that this can lead to:

if (x > y)
    exch(x,y);
    call_foobar(x,y);
else
    x = 0;

And says:

.. the exch() call completes the if statement and the call_foobar() call is executed unconditionally. Indenting in this case is worse than a sham, it actively deceives the programmer into thinking that the logic will work when it won’t.

Although I agree with his point, that mixing #defines that contain { } and if/else blocks that don’t can be dangerous, the example doesn’t actually compile. To trigger the bug you need:

if (x > y)
    exch(x, y);
    if (x)
        printf("hello!");
else
    x = 0;

Which after expansion of the macro looks logically like:

if (x > y) {
    .. guts of exch ..
}

if (x)
    printf("hello!");
else
    x = 0;

So it’s still nasty, but in the trivial if/else case you are safe.

Don’t miss some more of Paul’s excellent work.

Posted by mike on Thursday July 20th, 2006, tagged with ,

Comments are closed.