Omitting Parentheses from Macro Arguments

A macro definition that doesn't enclose its arguments in parentheses can create precedence problems:

#include <stdio.h>

#define FOURX(arg) ( arg * 4 )

main()

{

int val;

val = FOURX( 2 + 3 );

printf( "val = %d\n", val );

}

The FOURX macro in the program multiplies its argument by 4. The macro works fine if you pass it a single value, as in

val = FOURX( 2 );

but returns the wrong result if you pass it this expression:

val = FOURX( 2 + 3 );

QuickC expands the above line to this line:

val = 2 + 3 * 4;

Summary: Use parentheses to avoid precedence problems in macros.

Because the multiplication operator has higher precedence than the addition operator, this line assigns val the value 14 (or 2 + 12) rather than the correct value 20 (or 5 * 4).

You can avoid the problem by enclosing the macro argument in parentheses each time it appears in the macro definition:

#include <stdio.h>

#define FOURX(arg) ( (arg) * 4 )

main()

{

int val;

val = FOURX(2 + 3);

printf( "val = %d\n", val );

}

Now the program expands this line

val = FOURX(2 + 3);

into this one:

val = (2 + 3) * 4;

The extra parentheses assure that the addition is performed before the multiplication, giving the desired result.