From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 24366 invoked by alias); 12 Nov 2007 10:23:24 -0000 Received: (qmail 24348 invoked by uid 48); 12 Nov 2007 10:23:19 -0000 Date: Mon, 12 Nov 2007 10:23:00 -0000 Subject: [Bug c/34070] New: Wrong code for (int)x%4 X-Bugzilla-Reason: CC Message-ID: Reply-To: gcc-bugzilla@gcc.gnu.org To: gcc-bugs@gcc.gnu.org From: "simonmar at microsoft dot com" Mailing-List: contact gcc-bugs-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-bugs-owner@gcc.gnu.org X-SW-Source: 2007-11/txt/msg01037.txt.bz2 The following code generates the wrong result: -------------------- #include 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