Programming in C

(Barry) #1

310 Chapter 13 The Preprocessor


assigns the value of v^2 to y.What do you think would happen in the case of the state-
ment
y = SQUARE (v + 1);
This statement does notassign the value of (v + 1)^2 to yas you would expect. Because
the preprocessor performs a literal text substitution of the argument into the macro defi-
nition, the preceding expression would actually be evaluated as
y = v + 1 * v + 1;
which would obviously not produce the expected results.To handle this situation prop-
erly, parentheses are needed in the definition of the SQUAREmacro:
#define SQUARE(x) ( (x) * (x) )
Even though the preceding definition might look strange, remember that it is the entire
expression as given to the SQUAREmacro that is literally substituted wherever xappears
in the definition.With your new macro definition for SQUARE, the statement
y = SQUARE (v + 1);
is then correctly evaluated as
y = ( (v + 1) * (v + 1) );
The conditional expression operator can be particularly handy when defining macros.
The following defines a macro called MAXthat gives the maximum of two values:
#define MAX(a,b) ( ((a) > (b))? (a) : (b) )
This macro enables you to subsequently write statements such as
limit = MAX (x + y, minValue);
which would assign to limitthe maximum of x + yand minValue.Parentheses were
placed around the entire MAXdefinition to ensure that an expression such as
MAX (x, y) * 100
gets evaluated properly; and parentheses were individually placed around each argument
to ensure that expressions such as
MAX (x & y, z)
get correctly evaluated.The bitwise ANDoperator has lower precedence than the >opera-
tor used in the macro.Without the parentheses in the macro definition, the >operator
would be evaluated before the bitwise AND,producing the incorrect result.
The following macro tests if a character is a lowercase letter:
#define IS_LOWER_CASE(x) ( ((x) >= 'a') && ((x) <= 'z') )
and thereby permits expressions such as
if ( IS_LOWER_CASE (c) )
...
Free download pdf