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


Stephen Williams writes:

 > int
 > f()
 > {
 >   int j = 1;
 >   long i;
 >   for (i = 0x7ffffff0L; i <= 0x7fffffffL; i += 1) j++;
 >   return j;
 > }

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

Currently egcs loops forever which is fair enough since there is no
signed integer larger than 0x7fffffff on a 32-bit machine.  However,
I'm trying to get egcs to use low overhead looping instructions which
need to know the number of loop iterations before entering the loop.

If the behaviour of the loop is allowed to be undefined when the
iteration counter overflows then the task is much simpler :-) If the
loop must iterate forever, then extra code needs to be inserted around
the loop to test for this overflow condition.  For example, consider
the following where the final value is not known until run-time:

int i, j, size;
for (i = 0x7ffffff0; i <= size; i += 1) j++;


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

OK, what about this loop?  Will it terminate?

unsigned int i, j;
for (i = 0xfffffff0; i <= 0xffffffff; i += 1) j++;


Michael.


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