The #defineStatement 309
Unlike a function, you do not define the type of the argument yhere because you are
merely performing a literal text substitution and not invoking a function.
Note that no spaces are permitted in the #definestatement between the defined name
and the left parenthesis of the argument list.
With the preceding definition, you can write a statement such as
if ( IS_LEAP_YEAR (year) )
...
to test whether the value of yearwere a leap year, or
if ( IS_LEAP_YEAR (next_year) )
...
to test whether the value of next_yearwere a leap year. In the preceding statement, the
definition for IS_LEAP_YEARwould be directly substituted inside the ifstatement, with
the argument next_yearreplacing ywherever it appeared in the definition. So the if
statement would actually be seen by the compiler as
if ( next_year % 4 == 0 && next_year % 100 != 0 \
|| next_year % 400 == 0 )
...
In C, definitions are frequently called macros.This terminology is more often applied to
definitions that take one or more arguments. An advantage of implementing something
in C as a macro, as opposed to as a function, is that in the former case, the type of the
argument is not important. For example, consider a macro called SQUAREthat simply
squares its argument.The definition
#define SQUARE(x) x * x
enables you to subsequently write statements, such as
y = SQUARE (v);
to assign the value of v^2 to y.The point to be made here is that vcan be of type int,or
of type long, or of type float, for example, and the samemacro can be used. If SQUARE
were implemented as a function that took anintargument, for example, you couldn’t
use it to calculate the square of a doublevalue. One consideration about macro defini-
tions, which might be relevant to your application: Because macros are directly substitut-
ed into the program by the preprocessor, they inevitably use more memory space than
an equivalently defined function. On the other hand, because a function takes time to
call and to return, this overhead is avoided when a macro definition is used instead.
Although the macro definition for SQUAREis straightforward, there is an interesting
pitfall to avoid when defining macros. As has been described, the statement
y = SQUARE (v);