fabs(x) vs. (x) < 0 ? -(x) : (x)
Israel Pinkas
pinkas at mipos3.UUCP
Fri Jan 9 02:45:37 AEST 1987
In article <4477 at ut-ngp.UUCP> jjr at ngp.UUCP (Jeff Rodriguez) writes:
>What's the difference between
> double x, y;
> y = fabs(x)
>and
> #define abs(X) ((X) < 0 ? -(X) : (X))
> double x, y;
> y = abs(x);
>I.e., why isn't fabs() implemented as a macro?
K & R point out (in their discussion of min and max macros) that creating a
macro like this would cause X to be evaluted twice. While this might be OK
in most cases, consider if you had a function called read_float, which read
a float in from stdin. Then the call
y = fabs(read_float())
would call read_float() twice if it was implemented as a macro, but only
once if it was implemented as a function. Remembering that read_float()
reads a new float every time it is called, the macro implementation would
use the sign of the first number to determine whether to change the sign of
the second number.
-Israel
--
----------------------------------------------------------------------
UUCP: {amdcad,decwrl,hplabs,oliveb,pur-ee,qantel}!intelca!mipos3!pinkas
ARPA: pinkas%mipos3.intel.com at relay.cs.net
CSNET: pinkas%mipos3.intel.com
More information about the Comp.lang.c
mailing list