fabs(x) vs. (x) < 0 ? -(x) : (x)

meissner at dg_rtp.UUCP meissner at dg_rtp.UUCP
Tue Feb 17 10:02:01 AEST 1987


In article <68 at umich.UUCP> jtr485 at umich.UUCP (Johnathan Tainter) writes:
> In article <628 at sdchema.sdchem.UUCP>, tps at sdchem.UUCP (Tom Stockfisch) writes:
> > >You could implement fabs() as a macro as follows:
> > >    #define fabs(X)     ((_fabs = (X)), (_fabs < 0? -_fabs : _fabs))
> > >		/* ... */
> > This might not work for
> > 	fabs( x ) + fabs( y )
> > 		/* ... */
> 
> #define fabs(X)     (((_fabs = (X)) < 0? -_fabs : _fabs))
> 
> Again it requires the 'hidden' definition of _fabs but it does not have
> order of evaluation problems.
> 
> --j.a.tainter

It may solve that problem, but:

	fabs( fabs( y ) - 10.0 )

would still get the wrong answer.  In my opinion, the "best" way to do this
is to make fabs (and abs, min, max, etc.) builtin to the compiler.  In order
to allow people to still write their own "fabs" function, you might want
to have some special keyword (I use $builtin which is not a legimate standard
C identifier) to key in the compiler to use the builtin version of the library
function (which would compile down to the "right" instructions for your
machine, and no call overhead).  I also applaud C++'s inline keyword, which
should obviate the need for macro functions, which have the traditional
problems described above.
-- 
	Michael Meissner, Data General
	...mcnc!rti-sel!dg_rtp!meissner



More information about the Comp.lang.c mailing list