Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop from 0x0000 to 0xFFFF

Tags:

c#

loops

for-loop

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?

like image 806
Robert Avatar asked Oct 23 '08 19:10

Robert


1 Answers

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.

like image 96
Chris Marasti-Georg Avatar answered Oct 21 '22 14:10

Chris Marasti-Georg