Hacker News
points by kenferry 4 hours ago | 0 comments
I know it's "too clever", but if I'm writing code no one else will ever see,

  while (i --> 0) {
      // use array[i]
  }
easy to read (if not understand), and correct!
[–] krackers 4 hours ago
Oh I remember this from the classic SO post, but it was just presented as a funny trick. I never realized that it solves the issue mentioned in the article and there is a legitimate use-case for post-decrement in the comparison itself.

https://stackoverflow.com/questions/1642028/what-is-the-oper...

[–] StilesCrisis 2 hours ago
It's just spacing. X-- > 0 and X --> 0 are the same thing in C.
[–] 1718627440 2 hours ago
There is a reason postfix is the idiomatic way in C, it is the correct choice most of the time.
[–] hirvi74 1 hour ago
Swift (Lattner) was right, imo, to exclude both.
[–] golden-face 2 hours ago
Praise to the old gods and the new, why?!
[–] cryptonector 3 hours ago
It's a well-known (ish) idiom that nobody uses. It's very entertaining though, for sure. In some circles it's known as the down-to operator.
[–] viega 4 hours ago
I always use unsigned values and do:

  while (i-- != 0) { ... }
It's more clear than the most idiomatic way, which is to drop the explicit comparison:

  while (i--) { ... }
 
All of it is better than the clunky old for-loop syntax.
[–] chii 3 hours ago
if `i` ever gets modified inside the loop, and skips 0 (e.g., got decremented twice when it is at 1), then you might end up with an infinite loop?

Usually, this won't happen of course, but because `i` is not declared inside a for-loop, it must have been declared outside, and thus might even look like a regular variable that could be used by some "clever" coding to multipurpose it!

In any case, it's a niche worry i have, so i usually don't do it if i know there's a for loop that would do.

[–] mtklein 4 hours ago
I don't think it's too clever at all. Notably it works with both signed and unsigned i. Frankly if I see anyone doing anything other than this, they're wrong.
[–] stephencanon 4 hours ago
Always.

(Hi Ken!)