Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ What's the best way to end this 8-Bit for loop

Is it possible to write this for loop shorter or more elegant without using uint16_t? There is an overflow when i reaches 0xFF.

for (uint8_t i = 0; i <= 0xFF; i++)
{
    // do something
    if (i == 0xFF)
        break;
}
like image 345
Michael Koeppen Avatar asked Dec 19 '22 02:12

Michael Koeppen


1 Answers

To cover the full range, we just need to do the test after the body of the loop, so using a do...while is a nice fit here:

uint8_t i = 0;
do {
...
} while (i++ < 0xFF);
like image 123
Chris Uzdavinis Avatar answered Dec 24 '22 02:12

Chris Uzdavinis