C ++ What is the best way to end this 8-bit loop

Is it possible to write this for a loop shorter or more elegant without using uint16_t? When 0xFF is reached, overflow occurs.

for (uint8_t i = 0; i <= 0xFF; i++)
{
    // do something
    if (i == 0xFF)
        break;
}
+4
source share
3 answers

To cover the whole range, we just need to run the test after the body of the loop, so using do ... while this works well here:

uint8_t i = 0;
do {
...
} while (i++ < 0xFF);
+7
source

Since overflow for unsigned numbers is well defined, this loop can do this:

uint8_t i = 0;
do {
    // use i here
    i++;
} while (i);

i overflows (becomes 0) at the 256th iteration, while while stops because the condition is false.

: , 32- . → 32- , , >= 32- .

, 8- , 256-.

+3

Not the shortest, but the coolest way to do this is to declare an array with all possible values uint8_tand iterate over it.

#include <iostream>
#include <cstdint>
#include <limits>

namespace detail {
template<typename int_t, int_t cnt, bool not_done, int_t... rest>
struct range_impl {
    static constexpr auto& value = range_impl<int_t, cnt - 1,
        (cnt - 1) != std::numeric_limits<int_t>::min(), cnt, rest...>::value;
};

template<typename int_t, int_t cnt, int_t... rest>
struct range_impl<int_t, cnt, false, rest...> {
    static constexpr int_t value[] = { cnt, rest... };
};

template<typename int_t, int_t cnt, int_t... rest>
constexpr int_t range_impl<int_t, cnt, false, rest...>::value[];
} // detail

template<typename int_t>
struct range : public detail::range_impl<int_t, std::numeric_limits<int_t>::max(), true> {};

int main(int argc, char** argv) {
    for(uint8_t i: range<uint8_t>::value) {
        std::cout <<  (int) i << std::endl;
    }

    for(int8_t i: range<int8_t>::value) {
        std::cout <<  (int) i << std::endl;
    }
}

The structure rangegenerates an array at compile time. This code can be used for any integer type.

+1
source

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


All Articles