The following code generates the wrong result:

--------------------
#include <stdio.h>

int f(unsigned int x)
{
    printf("%x %d\n", x, (int)x);
    return ((int)x) % 4;
}

int main(int argc, char *argv[])
{
    printf("%d\n", f((unsigned int)(-1)));
    return 0;
}
--------------------

I expect this:

$ gcc-3.4.3 ctest33.c -Wall  && ./a.out
ffffffff -1
-1

and with gcc-4 and greater I get this:

$ gcc-4.2.1 ctest33.c -Wall  && ./a.out
ffffffff -1
3

Why do I think this is a bug?  Well, initially I thought I'd run into undefined
behaviour, but on closer reading of the C spec it seems the behaviour should be
implementation-defined, and gcc is not implementing the documented behaviour. 
Furthermore, gcc's behaviour is not consistent, as implementation-defined
behaviour should be.

The bug appears to be centered around conversion from unsigned to signed
integers.  We convert from unsigned to signed in f(), and the value passed is
0xffffffff.  The result is therefore implementation-defined (C99 6.3.1.3), and
gcc defines it (section 4.5 of the gcc docs) as: "For conversion to a type of
width N, the value is reduced modulo 2^N to be within range of the type".  I
presume this means that the value is truncated to N bits and the result
interpreted as twos-complement, which in this case should mean that (int)x is
-1, and the expression is (-1 % 4), which has value -1.

We can see from the printf output that (int)x has value -1.  Since this is its
implementation-defined value, it should have the same value in the expression
(int)x % 4.

Indeed, several minor variations of this code give the expected output. 
Substituting 0xffffffffU for x in the definition of f(), for example.

Optimisation level has no effect.  Bug also observed on i686-unknown-linux.


-- 
           Summary: Wrong code for (int)x%4
           Product: gcc
           Version: 4.2.1
            Status: UNCONFIRMED
          Severity: major
          Priority: P3
         Component: c
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: simonmar at microsoft dot com
 GCC build triplet: x86_64-unknown-linux-gnu
  GCC host triplet: x86_64-unknown-linux-gnu
GCC target triplet: x86_64-unknown-linux-gnu


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34070

Reply via email to