fabs(x) vs. (x) < 0 ? -(x) : (x)
tps at sdchem.UUCP
tps at sdchem.UUCP
Mon Feb 2 10:33:15 AEST 1987
In article <2550005 at hpisod2.HP> decot at hpisod2.HP (Dave Decot) writes:
>In article <4477 at ut-ngp.UUCP> jjr at ngp.UUCP (Jeff Rodriguez) writes:
>>Why isn't fabs() implemented as a macro [ (X) < 0 ? -(X) : (X) ]?
>
>You could implement fabs() as a macro as follows:
>
> #define fabs(X) ((_fabs = (X)), (_fabs < 0? -_fabs : _fabs))
>
>if _fabs were declared as a float in the math library.
>Dave
This might not work for
fabs( x ) + fabs( y )
because _fabs gets assigned twice in one expression and the two
comma expressions which result might get interleaved. There was
a major discussion in this group recently on whether the sub-expressions
a,b,c,d in
(a,b) + (c,d)
could be evaluated in the order
a c b d
Since the current defacto standard (K&R) is ambiguous on this point, I
think your method is not safe.
The real solution for this is to have an optimizer which can place
function calls inline. (There are complilers which can do this).
This even runs faster than your method
because it eliminates the store to _fabs.
|| Tom Stockfisch, UCSD Chemistry tps%chem at sdcsvax.UCSD
More information about the Comp.lang.c
mailing list