This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: INT_MIN % -1


Morten Welinder wrote:
> What is the value of  INT_MIN % -1  supposed to be, assuming 32-bit
> ints and two-complement representation.
> 
> C99 seems to be telling us two things about '%':
> 
> (1) It computes remainder for integer division.
> (2) "If the quotient  a/b  is representable, the expression
>     (a/b)*b + a%b  shall equal  a."
> 
> (2) is not useful for the case since the quotient is not representable.  I'd
> say that (1) means that the result should be zero, but that would be rather
> expensive to implement as you would have to test for -1 at runtime on i386,
> for example.
> 
> I would claim that there is no overflow in the calculation: both arguments
> and the result are perfectly representable as 32-bit ints.  The fact that
> the quotient of the same values, if performed, overflows is no more relevant
> that the fact that you can't take the square root of the two sides.
> 
> gcc 3.4 on solaris/sparc seems to get zero; gcc 3.3.1 on linux gives me a
> crash at runtime.  (Because the signed integer division instruction traps
> as documented.)
> 
> Comments?
> 
> Morten
> 
> 
> 
> -----------------------------------------------------------------------------
> 
> 
>>uname -a
> 
> SunOS troll 5.8 Generic_117350-11 sun4u sparc
> 
>>./a.out 
> 
> -2147483648 % -1 (const) = 0
> -2147483648 % -1 (non-const) = 0
> 
> -----------------------------------------------------------------------------
> 
> 
>>uname -a
> 
> Linux darter 2.4.21-243-default #1 Thu Aug 12 15:22:14 UTC 2004 i686 i686 i386 GNU/Linux
> 
>>./a.out 
> 
> -2147483648 % -1 (const) = 0
> Floating point exception
> 
> -----------------------------------------------------------------------------

/junk # uname -a
Linux (none) 2.4.25-Avtrex #152 Mon Nov 15 10:51:36 PST 2004 mips unknown
/junk # ./bla
-2147483648 % -1 (const) = 0
-2147483648 % -1 (non-const) = 0

Intel chose to trap.  Sun and MIPS chose not to.

I don't have the spec. in front of me, but I can imagine that it allows for
this.

If you want well defined behavior use something like java.  The JLS
specifies exactly what should happen in this case.

David Daney.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]