What's the do-while loop in the macro on slide 17 for?
Ryan Gordon's Linux Game Porting Guidance
Collapse
X
-
Originally posted by bison View PostWhat's the do-while loop in the macro on slide 17 for?
In particular, it ensures that the macro gets compiled as a single statement.
Take this code, for example:
if (COND)
foo();
else
bar();
if you replace foo(); with your MACRO(); call, it has to be exactly 1 statement in order to compile correctly. if your macro becomes 2 statements, the if statement will only hit the 1st one, the rest gets run unconditionally, and then the else below will break the compile for not matching up with an if statement anymore.
if your code always uses brackets, then i don't think it serves any purpose.Last edited by smitty3268; 17 January 2014, 02:45 PM.
Comment
-
-
Originally posted by mrugiero View PostMacros can't declare blocks of code in other way, I don't recall why, so it's a common hack to make a do-while(0) loop instead. As it's while(0), it only runs the first time.
I compiled it with
gcc -Wall -pedantic -std=c89 test.c
and it worked without the loop.
Comment
-
-
Originally posted by bison View PostThat must be a really old C thing, before my time. (!)
I compiled it with
gcc -Wall -pedantic -std=c89 test.c
and it worked without the loop.
Comment
-
-
Originally posted by bison View PostIt worked as expected. I retained the block, sans loop construct.
e.g.
//works
if (COND)
MACRO()
else
bar();
//fails because you can't declare if(COND) { ... }; else { } as valid.
if (COND)
MACRO();
else
bar();
Anyway, as discussed, the do-while(0) loop is only needed to help ensure corner conditions are satisfied. There are lots of ways the macro will work without it. It's only necessary to prevent some rare things from ever becoming an issue, especially since when that happens it can be fairly hidden from view and hard to track down. So it's just better to be safe than sorry as a general rule of thumb.
And there's no reason not to do it. The loop will always run exactly once, so it's trivial for compilers to optimize out any extra overhead. It's just a way to hack around a rough patch in the syntax of the language.Last edited by smitty3268; 18 January 2014, 04:46 AM.
Comment
-
Comment