Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettiest way to iterate all values of an unsigned integer

I want to iterate all possible values of an integer. This code does not work as the termination condition never becomes false:

for (uint32_t i = 0; i <= 0xFFFFFFFF; i++)
    std::cout << i << std::endl;

I've come up with this:

auto loopBody = [](uint32_t value)
{
    std::cout << value << std::endl;
};

uint32_t last = 0xFFFFFFFF;
for (uint32_t i = 0; i < last; i++)
    loopBody(i);

loopBody(last);

It is fairly ugly, though. Is there a prettier way to do this?

like image 569
Sunius Avatar asked Mar 12 '23 19:03

Sunius


1 Answers

I would use something like this:

uint32_t i = 0;
do
{
    // Your code here.
    i++;
}
while (i != 0);

I personally find it more elegant than a solution involving std::numeric_limits.


As @NicosC said, keep in mind that you should not do same trick with signed integers, because signed overflow is undefined behavior.
like image 162
HolyBlackCat Avatar answered Mar 23 '23 21:03

HolyBlackCat