do ... while(0) in macros

Joel Sherrill joel.sherrill at OARcorp.com
Wed Aug 8 12:36:39 UTC 2001


This explanation is dead on the money.  If you define
more than a single statement in a macro, it is a 
good habit to get into.  It is a good way to avoid 
bizarre and hard to debug problems like the one
Paul is describing.

One of the first RTEMS users taught me this
trick (thanks Tony :).

--joel

Paul Whitfield wrote:
> 
> Hi
> 
> The do{} while inside a macro is a common idiom
> to ensure that the macros always behave correctly
> when used in various different ways particularly
> with if statements
> 
> for example:
> 
> #define Macro() \
>         call_one(); \
>         call_two();
> 
> if (test)
>    Macro();
> 
> The the above macro would call function call_one
> if test was true, but would always call call_two.
> 
> while if we define the macro as
> 
> #define Macro do { \
>         call_one(); \
>         call_two(); \
>         } while(0);
> 
> Both call_one and call_two will be called only if test is true.
> 
> Hope that makes sense.
> 
> Regards
> Paul
> 
> 
> CARERI/SED wrote:
> >
> > There are many macros in RTEMS written like the following code:
> >
> >   do { \
> >     unsigned32 _stack; \
> >     \
> >     if ( (_isr) ) (_the_context)->eflags = CPU_EFLAGS_INTERRUPTS_OFF;
> > \
> >     else          (_the_context)->eflags = CPU_EFLAGS_INTERRUPTS_ON; \
> >
> >     \
> >     _stack = ((unsigned32)(_stack_base)) + (_size) - 4; \
> >     \
> >     *((proc_ptr *)(_stack)) = (_entry_point); \
> >     (_the_context)->ebp     = (void *) _stack; \
> >     (_the_context)->esp     = (void *) _stack; \
> >   } while (0)
> >
> > Could anybody explain the purpose of the "do ... while(0)" ?
> >
> > Thanks in advance,
> >
> > Guo
> 
> --
> -------------------------------------------------------
> Paul Whitfield
> Senior Software Engineer
> Microsol (Aust) Ltd
> 
> Phone: (+61) 08 9473 6646
> Fax:   (+61) 08 9473 6699

-- 
Joel Sherrill, Ph.D.             Director of Research & Development
joel at OARcorp.com                 On-Line Applications Research
Ask me about RTEMS: a free RTOS  Huntsville AL 35805
   Support Available             (256) 722-9985



More information about the users mailing list