Saturday, October 17, 2009

Nested Macro Definitions

A previously defined macro can be used as the value in another #define statement. The following is an example:
#define ONE 1
#define TWO (ONE + ONE)
#define THREE (ONE + TWO)
result = TWO * THREE;
Here the macro ONE is defined to be equivalent to the value 1, and TWO is defined to be equivalent to (ONE +
ONE), where ONE is defined in the previous macro definition. Likewise, THREE is defined to be equivalent to (ONE
+ TWO), where both ONE and TWO are previously defined.
Therefore, the assignment statement following the macro definitions is equivalent to the following statement:
result = (1 + 1) * (1 + (1 + 1));
WARNING
When you are using the #define directive with a macro body that is an expression, you need to enclose
the macro body in parentheses. For example, if the macro definition is
#define SUM 12 + 8
result = SUM * 10;

becomes this:
result = 12 + 8 * 10;
which assigns 92 to result.
However, if you enclose the macro body in parentheses like this:
#define SUM (12 + 8)
result = (12 + 8) * 10;
and produces the result 200, which is likely what you want.

No comments:

Post a Comment