Loop overflow
Stephen Williams
steve@icarus.com
Thu Oct 29 00:50:00 GMT 1998
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."
More information about the Gcc
mailing list