Computing the absolute value of an integer

Dan Kogai c60c-3cf at e260-3c.berkeley.edu
Fri May 4 22:19:50 AEST 1990


In article <11679 at june.cs.washington.edu> ka at cs.washington.edu (Kenneth Almquist) writes:
>I want a function that will compute the absolute value of any integer
>that can be stored in a variable of type int.  What makes this difficult
>is that on some machines the absolute value of the most negative integer
>will not fit in an int.  The following solution works on all machines I
>know of:
>
>	unsigned
>	my_abs(int a) {
>	      if (a >= 0)
>		    return a;
>	      else
>		    return -a;
>	}
>
>Does anyone know of machines on which this will fail?  Can anyone suggest
>a more portable implementation?
>					Kenneth Almquist

What's wrong with using a macro like the following

#define abs(x) (((x) >= 0) ? (x) : -(x))

	It should cause no problem if x is char|int|long and signed and abs(x)
itself is unneccesary if the type is unsigned.  And by using a macro
you save one jump and makes your code faster.  Even though you need to
stay away from macro your code could be as simple as

long abs(long x){
	return ((x >= 0) ? x: -x);
}
	I made it fnc returning long and takes 1 long arg because C has a 
copability of automatically aligning char|int|long appropriately.  You must
be careful though, when the conversion is from larger type to smaller
such as long to char.  Usually upper bits are truncated but sign extention
may cause some problem.  
	Remember it doesn't work in general if the variable is double|float
use fabs(x) if it's floating point variable.  But I think it's a macro, too,
that looks like

#define fabs(x) (double)(((double)(x) >= 0.0 ? (x) : (-x))

	I just took a look at /usr/include/math.h and it was even more
concice:

#define _abs(x) (x < 0 ? (-x): (x))

	In general your code looks too much like Pascal.  It's C and when in
C you'd better off program like C.  Happy coding!

---
##################  Dan The "I grok therefore I am God" Man
+ ____  __  __   +  (Aka Dan Kogai)
+     ||__||__|  +  E-mail:     dankg at ocf.berkeley.edu
+ ____| ______   +  Voice:      415-549-6111
+ |     |__|__|  +  USnail:     1730 Laloma Berkeley, CA 94709
+ |___  |__|__|  +              U.S.A
+     |____|____ +  Disclaimer: I'd rather be blackmailed for my long .sig
+   \_|    |     +              than give up my cool name in Kanji. And my
+ <- THE MAN  -> +              citizenship of People's Republic o' Berkeley
##################              has nothing 2 do w/ whatever I post, ThanQ.



More information about the Comp.lang.c mailing list