"for" loop appears to behaves abnormally when put in test to iterate through a whole range of "Integers", "Double", "byte", etc. However, this seems to be buggy but this situation arises due to "check arithmetic" that is used by default when incrementing the loop control variable beyond its maximum value which makes it value overflows and the loop restart's at the type's minimum value.
At first glance following example of for loop iteration seems to be fine and appears that it will iterate through the full range of the byte data type. However, the loop control variable can never exceeds than byte.MaxValue and it will reinitializes to byte.MinValue which makes it an infinite loop as predicate always evaluate it to true.
for (byte b = byte.MinValue; b <= byte.MaxValue; b++)
{
Console.WriteLine(b);
}
do
} while (byteVariable++ < byte.MaxValue);
At first glance following example of for loop iteration seems to be fine and appears that it will iterate through the full range of the byte data type. However, the loop control variable can never exceeds than byte.MaxValue and it will reinitializes to byte.MinValue which makes it an infinite loop as predicate always evaluate it to true.
for (byte b = byte.MinValue; b <= byte.MaxValue; b++)
{
Console.WriteLine(b);
}
Remedies
There are
several ways to resolve this problem. One of the most legible options is to use
a do-while loop,
like that presented in the code below. Here the byte value that replaces the
for loop's control variable is initialized to the minimum value before the loop
initiates. The body of the loop is the same as in the for loop. The crucial
part is the while predicate and the use of the increment operator (++).
As we are using the ++ operator's postfix version, the while
predicate is assessed before the variable is incremented. In the iteration
where byteVariable holds the maximum value of the data
type, the loops runs normally, outputting the value 255. The predicate is then
encountered and, as the value is no longer less than the maximum possible
value, the loop exits. byteVariable is then incremented and overflows,
resetting to zero. However, the loop has completed at this point so control
passes to the next line of code.
If you execute the code below you'll see that all of the
possible values from zero to 255 are displayed in the console.
byte byteVariable = byte.MinValue;do
{
Console.WriteLine(byteVariable);} while (byteVariable++ < byte.MaxValue);
No comments:
Post a Comment