This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: min/max macros
- To: Bill Ahlbrandt <bahlbr at icdata dot com>, egcs at cygnus dot com
- Subject: Re: min/max macros
- From: "Michael A. Benzinger" <mbenz at sabre dot com>
- Date: Thu, 11 Dec 1997 14:22:21 -0600
- Reply-To: egcs at cygnus dot com
At 11:14 AM 12/11/97 -0600, you wrote:
>#define max(a,b) (((a) > (b)) ? (a) : (b))
>#define min(a,b) (((a) < (b)) ? (a) : (b))
>
>After discovering that max in particular was not yielding the desired
results, I coded these macros as functions. All of my problems went away.
>
>Is it generally a bad plan to use macros like this? Are there any known
problems with egcs involving macros such as these?
Bill,
The functions are better than the macros for this very reason:
int x=2;
int y=1;
int z = max(x++,y);
Your intentions are to have 'z' equal to '2' and 'x' equal to '3'. However,
'x' is actually equal to '4'. Why? Because the macro code hides a nasty
gotcha. The code when expanded looks like this:
int z = (((x++) > (y)) ? (x++) : (y));
You will note that 'x++' is actuall evaluated twice. With a function of
the Standard Library function 'max', this will not happen. The argument
is only evaluated and incremented once, as you would expect.
Mike Benzinger
-------------------------------------------------------------
Michael A. Benzinger
Principal
SABRE Technology Solutions Phone: +1 817-264-6820
1 E. Kirkwood Blvd. Fax: +1 817-264-3504
Southlake, TX 76092 e-mail: mbenz@sabre.com
U.S.A. bzinger@iName.com