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



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




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