A case study of interger overflow's impact on iterators. when an unsigned integer is used in decrementing "for" loops. The loop unexpectedly iterates indefinitely if the loop had to terminate when the value becomes lesser than 0.
Since an unsigned integer is used, decrementing the variable to lesser than 0 will roll the value back to the
One possible solution is to terminate the loop when the value becomes greater than the initial assigned value or equal to the
Another solution would be to reserve 0 for the terminating condition. Note that the length should not be equal to
positive value range for signed integer: 0 to std::numeric_limits<signed int >::max()
positive value range for unsigned integer: 0 to std::numeric_limits<unsigned int >::max()
where, std::numeric_limits<signed int >::max() < std::numeric_limits<unsigned int >::max()
for(unsigned int i = length; i >= 0; --i)
{
//...
}
Since an unsigned integer is used, decrementing the variable to lesser than 0 will roll the value back to the
MAXIMUM_VALUE
that can be stored in the variable (depending on its size, usually 4 bytes - on 32 or 64 bit Windows), which is always >=0.One possible solution is to terminate the loop when the value becomes greater than the initial assigned value or equal to the
MAXIMUM_VALUE
.for(unsigned int i = length; i <= length; --i)
{
//...
}
for(unsigned int i = length; i != MAXIMUM_VALUE; --i)
{
//...
}
Another solution would be to reserve 0 for the terminating condition. Note that the length should not be equal to
MAXIMUM_VALUE
. Thus, a variable can be used to iterate a maximum count of
MAXIMUM_VALUE
.
for(unsigned int i = length + 1; i > 0; --i)
{
//Use i-1 ...
}
But, why use unsigned int at all? a signed integer does not have this problem. Because, unsigned integer have wider positive values range than the signed integer.positive value range for signed integer: 0 to std::numeric_limits<signed int >::max()
positive value range for unsigned integer: 0 to std::numeric_limits<unsigned int >::max()
where, std::numeric_limits<signed int >::max() < std::numeric_limits<unsigned int >::max()