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: Wed, 28 Oct 1998 15:38:05 -0800
- Cc: egcs at cygnus dot com
Trying to stump me?-)
m.hayes@elec.canterbury.ac.nz said:
> OK, what about this loop? Will it terminate?
> unsigned int i, j;
> for (i = 0xfffffff0; i <= 0xffffffff; i += 1) j++;
If UINT_MAX <= 0xffffffff, the loop will NOT terminate,
else if UINT_MAX > 0xffffffff the loop will terminate.
The relevant quote is from "6.1.2.5 Types"
"A computation involving unsigned operands can never overflow,
because a result that cannot be represented by the resulting
unsigned integer type is reduced modulo the number that is one
greater than the largest value that can be represented by the
resulting unsigned integer type."
Since i is unsigned int, "i <= UINT_MAX" no matter how many times "i += 1"
is executed. "i <= UINT_MAX" is true, so if "UINT_MAX <= 0xffffffff"
then "i <= 0xffffffff" and the loop test is never false.
If UINT_MAX > 0xffffffff, that type will be used to represent 0xffffffff
in the expression. "0xffffffff < i <= UINT_MAX" is possible, so the loop
will terminate.
Next question?-)
--
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."