5 ms·
Here's another one. Handy "syntax" that makes it possible to iterate an unsigned type from N-1 to 0. (Normally this is tricky.) for (unsigned int i = N; i -->
by nstbayless 4y ago
Here's another one. Handy "syntax" that makes it possible to iterate an unsigned type from N-1 to 0. (Normally this is tricky.)
for (unsigned int i = N; i --> 0;)
printf("%d\n", i);
This --> construction also works in JavaScript and so on.
- titzer 4y agoAFAICT this would parse as "(i--) > 0", there's no "-->" operator.
- texaslonghorn5 4y agohttps://stackoverflow.com/questions/1642028/what-is-the-operator-in-c https://stackoverflow.com/questions/1642028/what-is-the-oper...
- Jorengarenar 4y agoI was hesitant to put it on the list, but fine, you convinced me
- stonegray 4y agoIf you're gonna test the i--, shouldn't it fall through on zero anyway? for (unsigned int i = N; i--;){} unsigned int i = N; while(i--){ ... } Also I think I'm missing the tricky part. Couldn't this be a bog-standard for loop? for (unsigned int i = N - 1; i > 0; i--){ ... } The "downto" pseudooperator definitely scores some points for coolness and aesthetics, but there's no immediately obvious use case for me.
- Jorengarenar 4y agoThe former executes loop when `i` is 0. And we cannot change the comparison to `>=` in the later, because unsigned is always bigger or equal 0, thus we would get infinite loop.
- skribanto 4y agohow 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 ago
- deleted 4y ago[deleted]
- mtklein 4y agoIt's worth noting that this does also work on signed types, so it can be a kind of handy idiom to see while (N --> 0) { ... } and know it will execute N times no matter the details of the type of N.