Programming in C

(Barry) #1

308 Chapter 13 The Preprocessor


are perfectly valid.The name TWO_PIis defined in terms of the previously defined name
PI, thus obviating the need to spell out the value 3.141592654again.
Reversing the order of the defines, as in
#define TWO_PI 2.0 * PI
#define PI 3.141592654
is also valid.The rule is that you can reference other defined values in your definitions
provided everything is defined at the time the defined name is usedin the program.
Good use of defines often reduces the need for comments within the program.
Consider the following statement:
if ( year % 4 == 0 && year % 100 != 0 || year % 400 == 0 )
...
You know from previous programs in this book that the preceding expression tests
whether the variable yearis a leap year. Now consider the following define and the sub-
sequent ifstatement:
#define IS_LEAP_YEAR year % 4 == 0 && year % 100 != 0 \
|| year % 400 == 0
...
if ( IS_LEAP_YEAR )
...
Normally, the preprocessor assumes that a definition is contained on a single line of the
program. If a second line is needed, the final character on the line must be a backslash
character.This character signals a continuation to the preprocessor and is otherwise
ignored.The same holds true for more than one continuation line; each line to be con-
tinued must be ended with a backslash character.
The precedingifstatement is far easier to understand than the one shown directly
before it.There is no need for a comment as the statement is self-explanatory.The pur-
pose that the define IS_LEAP_YEARserves is analogous to that served by a function.You
could have used a call to a function named is_leap_yearto achieve the same degree of
readability.The choice of which to use in this case is completely subjective. Of course,
the is_leap_yearfunction could be made more general than the preceding define
because it could be written to take an argument.This would enable you to test if the
value of any variable were a leap year and not just the variable yearto which the
IS_LEAP_YEARdefine restricts you. Actually, you canwrite a definition to take one or
more arguments, which leads to our next point of discussion.

Arguments and Macros
IS_LEAP_YEARcan be defined to take an argument called yas follows:
#define IS_LEAP_YEAR(y) y % 4 == 0 && y % 100 != 0 \
|| y % 400 == 0
Free download pdf