delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/12/27/18:02:41

X-Authentication-Warning: delorie.com: mailnull set sender to djgpp-bounces using -f
Message-ID: <3C2B5F81.F4FCC6FA@acm.org>
From: Eric Sosman <esosman AT acm DOT org>
X-Mailer: Mozilla 4.72 [en] (Win95; U)
X-Accept-Language: en
MIME-Version: 1.0
Newsgroups: comp.os.msdos.djgpp
Subject: Re: DJGPP: #define problems
References: <daed704d DOT 0112271423 DOT 309fcdeb AT posting DOT google DOT com>
Lines: 53
Date: Thu, 27 Dec 2001 22:49:59 GMT
NNTP-Posting-Host: 12.91.4.93
X-Complaints-To: abuse AT worldnet DOT att DOT net
X-Trace: bgtnsc06-news.ops.worldnet.att.net 1009493399 12.91.4.93 (Thu, 27 Dec 2001 22:49:59 GMT)
NNTP-Posting-Date: Thu, 27 Dec 2001 22:49:59 GMT
Organization: AT&T Worldnet
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019