Computing the absolute value of an integer

Ken Yap ken at cs.rochester.edu
Thu May 10 02:45:13 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.
|
|Which in turn means that the operation "-a" on a variable a of any
|signed integer type is capable of causing overflow, which is allowed
|to cause the program to abort.  You are right to be worried.

I came across a bug that was caused by exactly this problem. In a
boundary case, a fp division by zero happened giving negative infinity
silently (another story). This was assigned to an integer. The problem
was that the author decided to do his own conversion to a string
instead of using printf or sprintf. The code said, in effect:

	if (x < 0)
		print leading -
		x = -x
	proceed as in positive case

Problem is, -maxint is -maxint, so the program printed a minus sign
and nothing else. Since this was a converter to Postscript, this bare
minus sign caused the printer to barf, aborting the job.

Moral of story? Make up your own.



More information about the Comp.lang.c mailing list