20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

310 Chapter 13 The Preprocessor<br />

assigns the value of v 2 to y.What do you th<strong>in</strong>k would happen <strong>in</strong> the case of the statement<br />

y = SQUARE (v + 1);<br />

This statement does not assign the value of (v + 1) 2 to y as you would expect. Because<br />

the preprocessor performs a literal text substitution of the argument <strong>in</strong>to the macro def<strong>in</strong>ition,<br />

the preced<strong>in</strong>g expression would actually be evaluated as<br />

y = v + 1 * v + 1;<br />

which would obviously not produce the expected results.To handle this situation properly,<br />

parentheses are needed <strong>in</strong> the def<strong>in</strong>ition of the SQUARE macro:<br />

#def<strong>in</strong>e SQUARE(x) ( (x) * (x) )<br />

Even though the preced<strong>in</strong>g def<strong>in</strong>ition might look strange, remember that it is the entire<br />

expression as given to the SQUARE macro that is literally substituted wherever x appears<br />

<strong>in</strong> the def<strong>in</strong>ition.With your new macro def<strong>in</strong>ition for SQUARE, the statement<br />

y = SQUARE (v + 1);<br />

is then correctly evaluated as<br />

y = ( (v + 1) * (v + 1) );<br />

The conditional expression operator can be particularly handy when def<strong>in</strong><strong>in</strong>g macros.<br />

The follow<strong>in</strong>g def<strong>in</strong>es a macro called MAX that gives the maximum of two values:<br />

#def<strong>in</strong>e MAX(a,b) ( ((a) > (b)) ? (a) : (b) )<br />

This macro enables you to subsequently write statements such as<br />

limit = MAX (x + y, m<strong>in</strong>Value);<br />

which would assign to limit the maximum of x + y and m<strong>in</strong>Value.Parentheses were<br />

placed around the entire MAX def<strong>in</strong>ition to ensure that an expression such as<br />

MAX (x, y) * 100<br />

gets evaluated properly; and parentheses were <strong>in</strong>dividually placed around each argument<br />

to ensure that expressions such as<br />

MAX (x & y, z)<br />

get correctly evaluated.The bitwise AND operator has lower precedence than the > operator<br />

used <strong>in</strong> the macro.Without the parentheses <strong>in</strong> the macro def<strong>in</strong>ition, the > operator<br />

would be evaluated before the bitwise AND,produc<strong>in</strong>g the <strong>in</strong>correct result.<br />

The follow<strong>in</strong>g macro tests if a character is a lowercase letter:<br />

#def<strong>in</strong>e IS_LOWER_CASE(x) ( ((x) >= 'a') && ((x)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!