min/max macros

Michael A. Benzinger mbenz@sabre.com
Thu Dec 11 13:03:00 GMT 1997


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



More information about the Gcc mailing list