Computing the absolute value of an integer
Kenneth Almquist
ka at cs.washington.edu
Thu May 3 15:07:40 AEST 1990
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
More information about the Comp.lang.c
mailing list