Unsigned char looping

What is an elegant way to do something like this without going into an infinite loop if i should be an unsigned char ?

 for (unsigned char i = 0; i < 256; ++i) { printf("%d\n", i); } 
+6
source share
3 answers
 unsigned char i = 0; do { printf("%u\n",i); }while(++i != 0); 

Increment the loop test and test it with the wrapped value.

+17
source

As a general rule: if your iterator variable must contain all values โ€‹โ€‹between 0 and "Uxxx_MAX", you have chosen a too narrow type for the algorithm.

Instead, you should have used uint16_t .

There are so many cases where you cannot use a large int type instead of your unsigned char. So let me ask you, your application is an embedded real-time system written for an 8-bit MCU, where did you find that this very loop is a performance bottleneck?

  • If so, write an obscure loop with uint8_t as an iterator type and comment on why you did it.
  • If not, use uint16_t or a larger integer type.
+3
source

Place check after body and before increment

 for (unsigned char i = 0; ; ++i) { printf("%d\n", i); if(i==255) break; } 

But then you can also do the following:

 unsigned char i = 0; while( ) { printf("%d\n", i); if(i==255) break; ++i; } 

Or even hit check:

 for (unsigned char i = 0; i++ < 255; ) { printf("%d\n", i); } 

They all check the value 255 before incrementing, instead of checking for zero after that, so if the variable was a CHAR or some macro that is currently limited to 256 but can be changed, they will still work, since they donโ€™t rely on overflow. Replace int there, and it still works.

+1
source

All Articles