Type-independent ABS

Chris Torek chris at mimsy.UUCP
Sun Oct 8 01:02:49 AEST 1989


[#define ABS(x) ((x) < 0 ? -(x) : (x))]

In an article whose referent was deleted by deficient news software,
I wrote:
>>on most machines, ABS(largest_negative_integer) is either a (compile
>>or run)-time trap or simply largest_negative_integer.

In article <1392 at cipc1.Dayton.NCR.COM> gmaranca at cipc1.Dayton.NCR.COM
(Gabriel Maranca) writes:
>... A complex expression may be passed as a parameter, as long
>as evaluating it three times doesn't cause problems.

Actually, x is evaluated exactly twice.

>If you have time, could you explain how is this problem resolved by
>the standard library function?

The short answer is `not'.  It is hard to give a single `best' answer
for -(-2147483647 - 1) on a 32-bit two's complement machine.  The
library routines I have seen simply negate it and do whatever the
machine's instruction set does on `impossible negation'.

>... I wonder how many standard library "functions" are implemented as 
>macros that could behave similarly? Or have such macros consistently 
>been avoided because of this side effect?

In general, the latter is true.  The proposed ANSI C standard requires
that side effects take place exactly once, which effectively prohibits
a straightforward macro version of abs() and labs().  One can still
write, e.g.,

	int abs(int);
	#define	abs(x)	__abs(x)
	static __inline int __abs(int x) { return x < 0 ? -x : x; }

in GCC.  I have used this in <stdio.h> to make putc() readable (`#ifdef'ed
on __GNUC__, of course).
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list