binary writes

  • Thread starter Thread starter sillyhat
  • Start date Start date
a bit off topic, but...

If I wanted to iterate through 0 to 255 using a byte variable,
then this first attempt would not work, as it gives an infinite loop.

for(byte i=0;i<=255;i++)
Console.Write(i + " ");

This next attempt does work but its would be nicer to have the exit
condition test within the for statement:

for(byte i=0;;i++)
{
Console.Write(i + " ");
if(i==255)break;
}

Is it possible to make the first loop work by tweaking the parameters
a little?

Ignore the fact that this might be an ideal candidate for a cast!

Hal
 
If I wanted to iterate through 0 to 255 using a byte variable,
then this first attempt would not work, as it gives an infinite loop.

for(byte i=0;i<=255;i++)
Console.Write(i + " ");

This next attempt does work but its would be nicer to have the test
within the for statement:

for(byte i=0;;i++)
{
Console.Write(i + " ");
if(i==255)break;
}

Is it possible to make the first loop work by tweaking the parameters
a little?

Ignore the fact that this might be an ideal candidate for a cast!

best I have managed so far:
for(byte i=0, abort=0 ; abort!=255 ;abort=i, i++)
{
Console.Write(i + " ");
}
 
On May 19, 3:26 pm, (e-mail address removed) wrote:

Is it possible to make the first loop work by tweaking the parameters
a little?

Not without more state, no.

Proof:
1) There are 256 states during which we want to enter the body of the
loop. If we need to capture the idea that the loop has finished,
that's another state - a total of 257.
2) A byte can only capture 256 distinct states.

You could do it with an extra variable, or even some weird tweaks and
Ignore the fact that this might be an ideal candidate for a cast!

A cast is a good way of capturing the extra state for the test and
then reducing it to the "interesting" subset of the state within the
loop.

Jon
 
Back
Top