Loop over 256 values โ€‹โ€‹using an 8-bit unsigned integer variable as a counter

So, I was just trying to fill the buffer with sequential numbers 0-255. I did not think very much about this and ended up in an endless loop.

uint8_t i; uint8_t txbuf[256]; for (i=0; i<256; i++) { txbuf[i] = i; } 

the problem is that i will never be 256 when it goes to zero after 255.

My question is, is there a way to make this loop without overloading i to a 16-bit value?

Note. I know that I could change the loop to i<255 and add another line for the last place, but I'm trying to figure out that there is a nicer way.

+5
source share
5 answers
 uint8_t txbuf[256]; uint8_t i = 0; do { txbuf[i] = i; } while (i++ != 255); 

or

 uint8_t txbuf[256]; uint8_t i = 255; do { txbuf[i] = i; } while (i--); 
+9
source

Use the do ... while to complete the action before checking the condition:

 uint8_t i = 0; uint8_t txbuf[256]; do { txtbuf[i] = i; } while(i++ < 255); 
+5
source

Do..while loops in other answers, probably you want, but if you specifically want to use a for loop, you can add a break statement:

 uint8_t i; uint8_t txbuf[256]; int main(void) { for (i=0; ; i++) { txbuf[i] = i; if (i == 255) break; } } 
+3
source

uint8_t is in the range from 0 to 255, so it does not become 256. Since we see that your array is also of type uint8_t, the value that it can save is also in the range 0-255, and that makes you a loop for values โ€‹โ€‹greater than 255?

Just keep your check as i<255 , and when you exit the loop, you know that the value of i is 255, use it accordingly.

Just use do while , as suggested by others.

+2
source

The following gcc (5.0) has a function to check if an overflow has occurred.

 uint8_t i = 0; uint8_t txbuf[256]; do { txbuf[i] = i; }while(!__builtin_add_overflow(i,1,i)); 

Read more at https://gcc.gnu.org/gcc-5/changes.html

+1
source

Source: https://habr.com/ru/post/1208448/


All Articles