[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

do ... while(0) in macros



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