[comp.lang.c] Type-independent absolute value

gmaranca@cipc1.Dayton.NCR.COM (Gabriel Maranca) (10/04/89)

Does anybody know why the abs() math function is not type independent? 
Or has this been changed in ANSI "C"?

I use the following macro instead of the standard library function:

#define ABS(x) (((long)(x) < 0L)? -(x) : (x))

This works for ints and longs, by casting the argument to a long for the
comparison, and then returning the absolute value of the argument with
its original type.

Is this non-ANSI or unportable? It works for me.

---
#Gabriel Maranca
#Gabriel.Maranca@cipc1.Dayton.NCR.COM
#...!uunet!ncrlnk!cipc1!gmaranca
-- 
#Gabriel Maranca
#Gabriel.Maranca@cipc1.Dayton.NCR.COM
#...!uunet!ncrlnk!cipc1!gmaranca

davidsen@crdos1.crd.ge.COM (Wm E Davidsen Jr) (10/05/89)

In article <1389@cipc1.Dayton.NCR.COM>,
	gmaranca@cipc1.Dayton.NCR.COM (Gabriel Maranca) writes:
|	[ she uses... ]
|  #define ABS(x) (((long)(x) < 0L)? -(x) : (x))

|	[ and asks... ]
|  Is this non-ANSI or unportable? It works for me.

  I don't see anything which is non-portable code, but have a few
suggestions:
	1. instead of -(x) use (-(x)).
	2. you might want to use (double) to work with more types
	3. you still have to be careful about what you use for an
	   argument to avoid things like ABS(x[m++]) which are only
	   evaluated once if ABS is a procedure.
-- 
bill davidsen	(davidsen@crdos1.crd.GE.COM -or- uunet!crdgw1!crdos1!davidsen)
"The world is filled with fools. They blindly follow their so-called
'reason' in the face of the church and common sense. Any fool can see
that the world is flat!" - anon

maart@cs.vu.nl (Maarten Litmaath) (10/05/89)

davidsen@crdos1.crd.ge.COM (Wm E Davidsen Jr) writes:
\In article <1389@cipc1.Dayton.NCR.COM>,
\	gmaranca@cipc1.Dayton.NCR.COM (Gabriel Maranca) writes:
\...
\|  #define ABS(x) (((long)(x) < 0L)? -(x) : (x))
\...
\	1. instead of -(x) use (-(x)). [...]

Why?  I can understand `-x' isn't a good idea, but `-(x)' seems OK to me.
-- 
   Did Andy Tanenbaum get his programming   |Maarten Litmaath @ VU Amsterdam: 
instruction from a Cereal box?  (Sam McCrea)|maart@cs.vu.nl, mcvax!botter!maart

davidsen@crdos1.crd.ge.COM (Wm E Davidsen Jr) (10/05/89)

In article <3497@solo10.cs.vu.nl>, maart@cs.vu.nl (Maarten Litmaath) writes:

|  Why?  I can understand `-x' isn't a good idea, but `-(x)' seems OK to me.

  I may be overly paranoid about semibroken compilers. In macros I try
to use enough parens to cover anything I might ever use, on any compiler
however poor. I had nothing special in mind, just CYA.
-- 
bill davidsen	(davidsen@crdos1.crd.GE.COM -or- uunet!crdgw1!crdos1!davidsen)
"The world is filled with fools. They blindly follow their so-called
'reason' in the face of the church and common sense. Any fool can see
that the world is flat!" - anon