This probably demonstrates the point where clever code is more likely to have bugs ...
This probably demonstrates the point where clever code is more likely to have bugs ...
Conceptually, it works through promotion. -1 is cast to unsigned/size_t before the test, which then succeeds. At the assembly level, a 32-bit -1 is 0xFFFFFFFF, which is also the result of the underflow of i, so it works at that level, too.
At any rate, it worked in the compiler I tried it with.
I, too, fail to understand how this is clever. Can someone enlighten me?
Whether that's a good thing is up for debate.
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.