Re: OFFTOPIC: 'do { ... } while (0)?'

Chris Adams (cadams@ro.com)
14 Apr 1998 20:34:37 GMT


According to David Schwartz <davids@webmaster.com>:
>>Why are so many macros written as: do { ... } while (0) rather than
>>as simply { ... } ?
>
>
> Because of the semantics of what a semicolon after it means. Consider:
>
>#define FOO1(a) do { baz(a); bar(); } while(0)
>#define FOO2(a) { baz(a); bar(); }
>
>if(x==1) FOO1(1); else FOO1(1);
>if(x==1) FOO2(1); else FOO2(2);
>
> See? Both look like they should work, but only FOO1 actually does.

And as long as you have optimization turned on, gcc will optimize the
do { } while (0) bit away, leaving just the code you wanted to begin
with.

-- 
Chris Adams - cadams@ro.com
System Administrator - Renaissance Internet Services
I don't speak for anybody but myself - that's enough trouble.

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu