Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!uwvax!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Type-independent ABS Keywords: abs labs Message-ID: <20042@mimsy.UUCP> Date: 7 Oct 89 15:02:49 GMT References: <1392@cipc1.Dayton.NCR.COM> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 40 [#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@cipc1.Dayton.NCR.COM> gmaranca@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 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@cs.umd.edu Path: uunet!mimsy!chris