logoalt Hacker News

viega • today at 1:46 AM • 2 replies • view on HN

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.

Replies

eps • today at 8:33 AM

There is nothing clearer about your way unless someone is just starting with C.

'while (i--)k is a shortcut, which might seem terse when one first encounters it, it is a well-established and trivial to understand construct. On the other hand, your embellishment only adds pointless friction when reading the code.

chii • today at 3:00 AM

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.