This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: min/max macros


At last, an egcs question that *I* can answer! :-)  (Unfortunately,
it's not really an egcs question, but a C/C++ question.  Anyway...)

 =>From: Bill Ahlbrandt <bahlbr@icdata.com>
 =>...
 =>I "coded" my own and used them as follows:
 =>
 =>#define max(a,b)	(((a) > (b)) ? (a) : (b))
 =>#define min(a,b)	(((a) < (b)) ? (a) : (b))
 =>
 =>Is it generally a bad plan to use macros like this?  Are there any
 =>known problems with egcs involving macros such as these? 

min/max macros are not inherently bad, as long as you understand that
they evaluate their arguments more than once.  For the simple case,
they work as you'd expect, but if you do something like:

		double x = min( sqrt(x), sqrt(y) );
		
		int		 a = 1;
		int		 b = 2;
		int		 c = max( a++, b++ );

you'll be inefficient (first example) or undefined (second example).

Min/max are better handled by inline functions; in c++ you can even
create a function template so that you can have min/max defined for
any type:

    template <class T> const T &
    min( const T &a, const T &b )
    {
        return (a < b) ? a : b;
    }

d.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]