[comp.lang.c] ABS for longs and ints

gmaranca@cipc1.Dayton.NCR.COM (Gabriel Maranca) (09/30/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 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

chris@mimsy.UUCP (Chris Torek) (10/01/89)

In article <1381@cipc1.Dayton.NCR.COM> gmaranca@cipc1.Dayton.NCR.COM
(Gabriel Maranca) writes:
>Does anybody know why the abs math function is not type independent?

Because it is a function, not a macro.

>Or has this been changed in ANSI "C"?

No.

>I use the following macro instead of the library function:
>
>#define ABS(x) (((long)(x) < 0L)? -(x) : (x))

The cast to long and the 0L are both unnecessary.  If left out, this
ABS will do its comparison in whatever type x has.

Note that ABS(k++) and the like will do `mysterious' things, and
that on most machines, ABS(largest_negative_integer) is either
a (compile or run)-time trap or simply largest_negative_integer.

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

It is not part of the proposed ANSI standard, but it is portable.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

flaps@dgp.toronto.edu (Alan J Rosenthal) (10/01/89)

gmaranca@cipc1.Dayton.NCR.COM (Gabriel Maranca) writes:
>#define ABS(x) (((long)(x) < 0L)? -(x) : (x))
...
>Is this non-ANSI or unportable? It works for me.

It is portable but will only work for ints and longs.  But the following
is portable and will work for all types, including unsigned long, double,
and long long if it exists:

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

The zero will get promoted to the correct type.

Like hey folks, C fully supports "mixed mode" arithmetic.  It isn't fortran.

ajr

--
Vs encr vf n xvaq bs frk, gura n chapu va gur zbhgu vf n xvaq bs gnyxvat.

gwyn@smoke.BRL.MIL (Doug Gwyn) (10/01/89)

In article <1381@cipc1.Dayton.NCR.COM> gmaranca@cipc1.Dayton.NCR.COM (Gabriel Maranca) writes:
>Does anybody know why the abs math function is not type independent? Or has
>this been changed in ANSI "C"?

That's just the way it's always been.

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

Feel free.  Note that if its argument has side effects, funny
behavior may occur.