...
Code Block | ||
---|---|---|
| ||
if (x > y)
SWAP(x,y); /* Branch 1 */
else
do_something(); /* Branch 2 */
{code:bgColor=#ffcccc}
Following macro |
Following macro expansion,
...
however,
...
this
...
code
...
is
...
interpreted
...
as
...
an
...
if-statement
...
with
...
only
...
one
...
branch:
Code Block | ||
---|---|---|
| ||
if (x > y) { /* Single-branch if-statement!!! */ int tmp; /* The one and only branch consists */ tmp = x; /* of the block. */ x = y; y = tmp; } ; /* empty statement */ else /* ERROR!!! "parse error before else" */ do_something(); |
The
...
problem
...
is
...
the
...
semi-colon
...
';'
...
following
...
the
...
block.
...
Compliant Solution
Wrapping the macro inside a do-while
...
loop
...
mitigates
...
the
...
problem.
Code Block | ||||
---|---|---|---|---|
| =
| |||
}
/*
* Swaps two values.
* Requires tmp variable to be defined.
*/
#define SWAP(x, y) \
do { \
tmp = x; \
x = y; \
y = tmp; } \
while (0)
|
...