I don't necessarily think that for loops are inherently easier to read than while loops, but I think if you're doing a typical incrementing/decrementing-iterator-variable loop it probably makes more sense to use for since that's the reason for exists.
I'll typically only use while if I need to check some other sort of condition that doesn't fall neatly into that pattern. As an example, I'm currently building a syntax highlighter for the web (mostly for fun), and I have a method like this:
tokenize tries to match the beginning of the line (which is a string) for a number of different regex patterns, assigns the match a token, and then removes the match from the front of the line. So each time it's done, the line will be a little shorter, but it's impossible to know by how much ahead of time, which makes the while loop the correct tool for the job in this particular case. That's my thinking anyway.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I don't necessarily think that
for
loops are inherently easier to read thanwhile
loops, but I think if you're doing a typical incrementing/decrementing-iterator-variable loop it probably makes more sense to usefor
since that's the reasonfor
exists.I'll typically only use
while
if I need to check some other sort of condition that doesn't fall neatly into that pattern. As an example, I'm currently building a syntax highlighter for the web (mostly for fun), and I have a method like this:tokenize
tries to match the beginning of the line (which is a string) for a number of different regex patterns, assigns the match a token, and then removes the match from the front of the line. So each time it's done, the line will be a little shorter, but it's impossible to know by how much ahead of time, which makes thewhile
loop the correct tool for the job in this particular case. That's my thinking anyway.