Programming in C

(Barry) #1
500 Appendix D Common Programming Mistakes

because the compiler will see this statement after preprocessing:
if ( value == 999; )
...


  1. Omitting parentheses around arguments in macro definitions.
    Example
    #define reciprocal(x) 1 / x
    ...
    w = reciprocal (a + b);


The preceding assignment statement would be incorrectly evaluated as
w = 1 / a + b;


  1. Leaving a blank space between the name of a macro and its argument list in the #define
    statement.
    Example
    #define MIN (a,b) ( ( (a) < (b) )? (a) : (b) )


This definition is incorrect, as the preprocessor considers the first blank space after
the defined name as the start of the definition for that name. In this case, the
statement
minVal = MIN (val1, val2);

gets expanded by the preprocessor into
minVal = (a,b) ( ( (a) < (b) )? (a) : (b) )(val1,val2);

which is obviously not what is intended.


  1. Using an expression that has side effects in a macro call.
    Example
    #define SQUARE(x) (x) * (x)
    ...
    w = SQUARE (++v);


The invocation of the SQUAREmacro causes vto be incremented twicebecause this
statement is expanded by the preprocessor to
w = (++v) * (++v);

23 0672326663 AppD 6/10/04 2:00 PM Page 500

Free download pdf