Re: fake loop

From: Martin Mačok (martin.macok@underground.cz)
Date: Fri Aug 03 2001 - 11:11:12 EST


On Fri, Aug 03, 2001 at 09:57:34AM -0600, Andrey Ilinykh wrote:
> #define prepare_to_switch() do { } while(0)
>
> Who can explain me a reason for these fake loops?

http://kernelnewbies.org/faq/index.php3#dowhile.xml

There are a couple of reasons:

    * (from Dave Miller) Empty statements give a warning from the compiler so
        this is why you see #define FOO do { } while(0).
    * (from Dave Miller) It gives
        you a basic block in which to declare local variables.
    * (from Ben Collins) It allows you to use more complex macros in
        conditional code. Imagine a macro of several lines of code like:

#define FOO(x) \
        printf("arg is %s\n", x); \
        do_something_useful(x);

      Now imagine using it like:

if (blah == 2)
                FOO(blah);

      This interprets to:

if (blah == 2)
                printf("arg is %s\n", blah);
                do_something_useful(blah);;

      As you can see, the if then only encompasses the printf(), and the
do_something_useful() call is unconditional (not within the scope of the if),
like you wanted it. So, by using a block like do{...}while(0), you would get
this:

if (blah == 2)
                do {
                        printf("arg is %s\n", blah);
                        do_something_useful(blah);
                } while (0);

      Which is exactly what you want.

Have a nice day

-- 
   Martin Mačok
  underground.cz
    openbsd.cz
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/



This archive was generated by hypermail 2b29 : Tue Aug 07 2001 - 21:00:28 EST