Type-independent ABS

Michael Meissner meissner at tiktok.dg.com
Wed Oct 11 00:42:10 AEST 1989


In article <20042 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
| 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).

I know the above example is to demostrate the use of __inline, but
with GNU C, it does support a builtin abs function (though for some
reason it's not documented).  You can simplify the above to:

	#ifdef __GNUC__
	extern int abs(int);
	#define abs(x) __builtin_abs(x)
	#endif

Some machines have fast ways of doing abs (as compared to the branch
method above).  Gnu C also has the following builtin functions related
to abs:

	__builtin_labs(long)
	__builtin_fabs(double)
--
Michael Meissner, Data General.
Uucp:		...!mcnc!rti!xyzzy!meissner		If compiles were much
Internet:	meissner at dg-rtp.DG.COM			faster, when would we
Old Internet:	meissner%dg-rtp.DG.COM at relay.cs.net	have time for netnews?



More information about the Comp.lang.c mailing list