Re:Counting up vs. counting down
by masklinn on Thursday November 19, 2015 @10:30AM
(#10595259)
`-1` will underflow, so you'll effectively have a SIZE_MAX. The counting down will similarly underflow, reach SIZE_MAX and stop the iteration.
[ Parent
| on HN ]
Re:Counting up vs. counting down
by untothebreach on Thursday November 19, 2015 @10:49AM
(#10595368)
Wouldn't it be clearer to just put `i != SIZE_MAX` then? I understand that anyone experienced with C probably wouldn't be confused by this, but you might as well sacrifice a couple characters in exchange for saving brain cycles, right?
I don't know if it'd be clearer. It'd be a better representation of what actually happens but would read very strangely. `!= -1` would make a reader think "shouldn't go below 0" and only on closer inspection would you wonder what actually happens, `!= SIZE_MAX` would probably make any reader stop and scratch their head.
Whether that's a good thing is up for debate.
if you are thinking about "<0" on an unsigned type, you better be scratching your head already.
Re:Counting up vs. counting down
by Lagged2Death on Thursday November 19, 2015 @11:39AM
(#10595725)
I'd expect anyone experienced with C would say that making such casual, deliberate use of the underflow for such a trivial purpose is pretty foolish, the mark of a developer too clever for his own good. I thought the author was perhaps suggesting this with sarcasm: "Wizened sourcerers" and "full clever." But maybe not.
C's variable promotion system is invisible and silent and in my experience a frequent source of bugs in exactly this case (tests in for loops), which is why there's enough meat here for a blog post. It's usually easy to avoid the promotion issue by using the same type for the loop variable and its test condition. In cases like this, sometimes it's better to just use a straightforward and obvious while() loop instead of a correct but tortured for() loop. That makes the relationship between the loop variable updates and the loop body controllable and explicit.