Page 71 - Programming Microcontrollers in C
P. 71
56 Chapter 1 Introduction to C
The second line of code
#define abs(t) (((t)>=0) ? (t) : -(t))
is called a macro definition. In this case, the macro definition has the
appearance of a simple function. This function will calculate the ab
solute value of the argument t. The absolute value of the argument is
a positive value. If the argument is positive, it is returned unchanged.
If it is negative, it is multiplied by –1 before it is returned. A macro
definition is a type of character expansion. Whenever the function
abs(x) is found in the code, the character string (((x)>=0) ?
(x) : -(x)) is put in its place. The argument x can be any valid
C expression. This function returns the absolute value of its argu
ment. The macro definition
#define square(t) (t)*(t)
returns the square of t. Since these arguments can be any valid C
expression, it is necessary to be cautious when writing the macro defi
nitions. Suppose that the parentheses were left out of the above
expression, and the macro were written
#define square(t) t*t
Also suppose that the code using this function were as follows:
x=square(y+3);
The character expansion of this expression would be
x=y+3*y+3;
The result of this calculation is 4*y+3 and not (y+3)*(y+3) as
expected. When writing macro definitions, surround all arguments
and functions created by the macro with parentheses so that all argu
ments are evaluated prior to use in the macro definition function.
Another problem can sneak into your code through improperly
written macros. Suppose that you want a macro that doubles the value
of its argument. Such a macro could be written
#define times_two(x) (x)+(x)
This macro when expanded in the following expression
x = 7*times_two(y);