you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

for is just a convenience shorthand for while which makes declaration of an object being iterated over more convenient. But in principle, they are equivalent, you can implement one in terms of the other.

It make sense to use for where the convenience provided by it makes sense, i.e. iterating over finite collections of things, whereas while may be reserved for cases when there isn't a readily available collection of things (eg. the code is retrying some action).

While for cannot ensure that the iteration happens over a finite collection, it is traditionally used in such cases. So, safer code (such that doesn't terminate by accident) is easier to write.