linux-kernel.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* Loop condition question. (GCC bug?)
@ 2011-03-10  2:05 Tetsuo Handa
  0 siblings, 0 replies; only message in thread
From: Tetsuo Handa @ 2011-03-10  2:05 UTC (permalink / raw)
  To: linux-kernel

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?

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2011-03-10  2:05 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2011-03-10  2:05 Loop condition question. (GCC bug?) Tetsuo Handa

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).