2 ms·
This is the fastest way to write a loop in pretty much any language _if_ order is not imperative and is very well understood by any developer worth their salt.
by goldenkey 13y ago
This is the fastest way to write a loop in pretty much any language _if_ order is not imperative and is very well understood by any developer worth their salt.
> I tend to favor pre-decrement in for loops as a general pattern, but of course in your code it must be post or it will break on an empty string.
That makes absolutely no sense. It's post-increment so it runs for i=0, could have easily been:
for (int i = strlen(str); --i >= 0;)
http://codepad.org/kd3oOBAb http://codepad.org/kd3oOBAb <-- fiddle around beginner ;-)
- unwind 13y agoHuh? I'm aware that there can be benefits to looping backwards. There can also be (cache-related) drawbacks. "It's post-increment so it runs for i=0" is probably exactly what I meant, you needed to use post-decrement (not increment) since otherwise it would break. Of course it can be re-written like you did now, but then you added the >= 0 part which was implicit in your first comment. Its omission made it important to pick post-decrement or it would break on an empty string just as I said. My entire point was that it's beyond most beginners to rely on fairly subtle things like that. Not sure why you're so condescending, I certainly didn't try to call you a beginner, it was the other way around: your code was not very beginner-esque, but the original article was about how a C beginner might write a simple loop and be surprised.
- goldenkey 13y agoI see what you mean now, I was quick to judge, wrongly albeit. Sorry about that.
- ygra 13y agoIt's not foolproof, though. Take a beginning C++ programmer who heard that type inference is all the rage now: for (auto i = strlen(str); --i >= 0;) and you got yourself an infinite loop. One that isn't so easy to see or diagnose either, unless you know that strlen returns size_t. Which a beginner might not.