This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Loop overflow


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."




Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]