This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Loop overflow
- To: Michael Hayes <m dot hayes at elec dot canterbury dot ac dot nz>
- Subject: Re: Loop overflow
- From: Stephen Williams <steve at icarus dot com>
- Date: Tue, 27 Oct 1998 17:31:42 -0800
- Cc: egcs at cygnus dot com
This is how I read it.
int
f()
{
int j = 1;
long i;
for (i = 0x7ffffff0L; i <= 0x7fffffffL; i += 1) j++;
return j;
}
6.3 Expressions
If an _exception_ occurs during the evaluation of an expression
(that is, if the result is not mathematically defined or not in the
range of representable values for its type) the behavior is undefined.
If LONG_MAX == 0x7fffffff, then when "i" gets to 0x7fffffff, the expression
"i += 1" has undefined behavior. There is nothing that I can find that
says that signed arithmetic is 2s complement. (It *is* explicit that unsigned
arithmetic is modulo the MAX value for the type.)
However, the behavior only becomes undefined after the 16th iteration.
A math teacher would say that the loop is undefined. f() may return 16,
it may loop forever, it may abort the program.
And here I think we get beyond the law and into the realm of philosophy:-)
Is a program undefined if its evaluation is certain to lead to an undefined
state?
--
Steve Williams "The woods are lovely, dark and deep.
steve@icarus.com But I have promises to keep,
steve@picturel.com and lines to code before I sleep,
http://www.picturel.com And lines to code before I sleep."