Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added additional NCE showing problem with #define SWAP(x,y) { int tmp; tmp=x; x=y; y=tmp; }

...

Code Block
bgColor#ffcccc
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
bgColor#ffcccc

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
bgColor
#ccccff
}
/*
 * Swaps two values.
 * Requires tmp variable to be defined.
 */
#define SWAP(x, y) \
  do { \
    tmp = x; \
    x = y; \
    y = tmp; } \
  while (0)

...