Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!umich!samsung!usc!wuarchive!udel!rochester!ken From: ken@cs.rochester.edu (Ken Yap) Newsgroups: comp.lang.c Subject: Re: Computing the absolute value of an integer Message-ID: <1990May9.164513.20739@cs.rochester.edu> Date: 9 May 90 16:45:13 GMT References: <11679@june.cs.washington.edu> <1990May4.121950.22726@agate.berkeley.edu> <1990May5.011945.9284@sq.sq.com> Reply-To: ken@cs.rochester.edu Organization: University of Rochester Computer Science Department Lines: 25 Address: Rochester, NY 14627, (716) 275-1448 |? 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.