This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
INT_MIN % -1
- From: terra at gnome dot org (Morten Welinder)
- To: gcc at gcc dot gnu dot org
- Date: Mon, 29 Nov 2004 16:59:14 -0500 (EST)
- Subject: INT_MIN % -1
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
-----------------------------------------------------------------------------
#include <stdio.h>
#include <limits.h>
#define A INT_MIN
#define B -1
static int a = A;
static int b = B;
int
main (int argc, char **argv)
{
printf ("%d %% %d (const) = %d\n", A, B, A % B);
printf ("%d %% %d (non-const) = %d\n", a, b, a % b);
return 0;
}