BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Looping Through an Entire Integer Range

As most for loops rely on a predicate that is based upon the loop control variable, iterating through an entire integer range is not as simple as it may first seem. An easy way to overcome the problems caused is to use a while loop instead.

For Loops and Integer Overflows

If you need to loop through the entire range of values provided by one of the integer types, using a for loop can be more complex than necessary. If you want to loop from the minimum to the maximum value, a simple for loop is not always appropriate. This is because you will generally use a predicate within the loop that checks that the loop control variable is less than, or less than or equal to, a specific value. If the value you are comparing to is the maximum for the type, the loop control variable will never exceed the maximum and you will create an infinite loop. This is due to the checked arithmetic that is used by default; when incrementing the loop control variable beyond the maximum, its value overflows and the loop restarts at the type's minimum value.

You can see the problem in the loop below. At first glance, it appears that this will iterate through the full range of the byte data type. However, the loop control variable can never be larger than byte.MaxValue, meaning that the predicate always evaluates to true and the loop never terminates.

for (byte b = byte.MinValue; b <= byte.MaxValue; b++)
{
    Console.WriteLine(b);
}

There are several ways to resolve this problem. One of the most readable options is to use a do-while loop, like that shown in the code below. Here the byte value that replaces the for loop's control variable is initialised to the minimum value before the loop commences. The body of the loop is the same as in the for loop. The key 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 evaluated before the variable is incremented. In the iteration where b 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. b 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 b = byte.MinValue;
do
{
    Console.WriteLine(b);
} while (b++ < byte.MaxValue);
21 August 2012