Loop condition question. (GCC bug?)

From: Tetsuo Handa
Date: Wed Mar 09 2011 - 21:05:47 EST


I was trying to figure out what happens to "for (i = 0; i < n i++)" loop when
"i is int" and "sizeof(i) == 4" and "n is unsigned long" and "sizeof(n) == 8"
and "n is larger than INT_MAX" (in order to determine whether such comparison
can cause "int i" to become negative value).

----- Start of source code -----
#include <linux/module.h>
#include <linux/sched.h>

static int __init test_init(void)
{
int i;
unsigned long n = 2147483649UL;
for (i = 2147483646; i < n; i++) {
printk(KERN_INFO "*** i=%d\n", i);
if (signal_pending(current))
break;
}
return -EINVAL;
}

module_init(test_init);
MODULE_LICENSE("GPL");
----- End of source code -----

# gcc --version
gcc (GCC) 4.5.1 20100924 (Red Hat 4.5.1-4)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

# uname -a
Linux localhost.localdomain 2.6.35.11-83.fc14.x86_64 #1 SMP Mon Feb 7 07:06:44 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux

I got a strange behavior around the boundary.
Above program prints

*** i=2147483647
*** i=2147483647
*** i=2147483647
*** i=2147483647

line forever.

If the loop is "for (i = 2147483645; i < n; i++)" instead of
"for (i = 2147483646; i < n; i++)", it prints only

*** i=2147483645
*** i=2147483646
*** i=2147483647

lines.

If I use "volatile int i;" instead of "int i;", the
"for (i = 2147483646; i < n; i++)" loop prints only

*** i=2147483646
*** i=2147483647

lines.

Is this a compiler bug?

Also, is the "for (i = 0; i < n; i++)" loop guaranteed to stop at
i == 2147483647 if n is larger than 2147483648?
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/