Mail Archives: djgpp/2001/12/27/18:02:41
Matt wrote:
> [...]
> #include <stdio.h>
> #define BASEVAL1 233
> #define BASEVAL2 BASEVAL1 + 29
> #define BASEVAL3 233
> #define BASEVAL4 BASEVAL1 + 57
>
> int main(void)
> {
> printf("baseval1 [233] = %d\n", BASEVAL1);
> printf("baseval2 [262] = %d\n\n", BASEVAL2);
> printf("baseval3 [233] = %d\n", BASEVAL3);
> printf("baseval4 [290] = %d\n\n", BASEVAL4);
>
> /* up to this point the define's are ok but when the math is done
> on
> the next line it seems to be treating the result as an unsigned
> char
> data type. */
> printf("baseval4 - baseval2 [28] = %d\n\n", BASEVAL4 - BASEVAL2);
The #define doesn't perform any math at all; it simply arranges to
replace each subsequent appearance of the macro name with its
definition.
The expression `BASEVAL4 - BASEVAL2' becomes `BASEVAL1 + 57 - BASEVAL1 +
29'
which in turn becomes `233 + 57 - 233 + 29'. No more macro names
remain,
so the compiler evaluates the resulting expression and (presumably) gets
86 as a result.
This is one of the reasons people recommend surrounding non-atomic
macro definitions with parentheses, e.g.
#define BASEVAL1 233
#define BASEVAL2 (BASEVAL1 + 29)
#define BASEVAL3 233
#define BASEVAL4 (BASEVAL1 + 57)
The parentheses are part of the macro definition and hence part of the
replacement, so the first step in expanding `BASEVAL4 - BASEVAL2' is
`(BASEVAL1 + 57) - (BASEVAL1 + 29)', quite a different expression from
the one you originally obtained. Another example where the parens
make a crucial difference is `2 * BASEVAL2', or `BASEVAL2 * BASEVAL4',
and so forth.
By the way, did you really mean to define BASEVAL4 in terms of
BASEVAL1 rather than BASEVAL3?
--
Eric Sosman
esosman AT acm DOT org
- Raw text -