Loop from 0x0000 to 0xFFFF
Question
I'd like a loop that uses a UInt16 (ushort) to loop through all of its values. However, this doesn't do it:
for( ushort i = 0; i < UInt16.MaxValue; i++ )
{
// do something
}
The problem is that the loop will quit when i == 0xFFFF and not "do something". If I change the 'for' statement to "for(ushort i = 0; i <= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF.
I could make 'i' an int and cast it or assign it to a ushort variable in the loop.
Any suggestions?
Solution
Use a do...while
loop
ushort i = 0;
do
{
// do something
} while(i++ < UInt16.MaxValue);
There is an interesting discussion of testing loops at the top vs. the bottom here.
OTHER TIPS
UInt16.MaxValue
evaluates to 0xffff
, not 0x10000
. I think you can do this with a do
/while
loop, as a variation on burkhard1979's answer.
ushort i = 0;
do {
...
} while (++i != 0);
You could simply replace the for by a do-while loop.
ushort i = 0;
do
{
i++;
...
} while(i!=UInt16.MaxValue);
does it have to be a short? why not just
for(int i = 0;i<=0xFFFF;i++)
{
//do whatever
}
Assuming that your code suffers from an off by one error (the current code, stops just before having the final value evaluated. Then the following might answer you.
Very simple, as your counter is a 16 bit unsigned integer, it can not have values bigger than 0xffff
, as that value is still valid, you need to have some value that extends beyond that as the guard. However adding 1
to 0xffff
in 16 bits just wraps around to 0
. As suggested, either use a do while loop (that does not need a guard value), or use a larger value to contain your counter.
ps. Using 16 bit variables on modern machines is actually less efficient than using 32 bit variables as no overflow code needs to be generated.