4 ms·
how would you iterate over every possible value of a unsigned int?
by skribanto 4y ago
how would you iterate over every possible value of a unsigned int?
- mtklein 4y agoUsually I use a do-while loop, unsigned char x = 0; do { printf("%d\n", x); } while (++x);
- NoZebra120vClip 4y agoThe unary complement operator should get you there: unsigned int x = 0; const unsigned int max = ~x; while (x <= max) { calc(x++); } Or, #include <limits.h> const unsigned int max = UINT_MAX;
- kstenerud 4y agoOr if you only wanted to iterate halfway: unsigned int x = 0; while (x < ~x) { calc(x++); } Or going down: unsigned int x = ~0; while (x > ~x) { calc(x--); }
- NoZebra120vClip 4y agoBy "halfway", did you mean "off by one"?
- kstenerud 4y agono
- mnaydin 4y agoThis is equivalent to while (1) { calc(x++); } which is an infinite loop, since the expression x <= max is always true
- NoZebra120vClip 4y agoHeh! Good catch! That is what I get for not testing. After UINT_MAX, x wraps around to 0.