What’s the real difference between a foreach and for loop if either can get the same job done? I’m learning C++ and apparently there is no foreach loop for its arrays 🙁
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is no “foreach” language construct in C++, a least not literally. C++11 introduces something that’s “as good as” a foreach loop, though.
The traditional
forloop has something to do with evaluating conditions and performing repeated operations. It’s a very general control structure. Its most popular use is to iterate over container or array contents, but that’s just a tiny fraction of what you can do with it.A “foreach” loop, on the other hand, is explicitly designed to iterate over container elements.
Example:
In the second for, we use a traditional
forloop to increment an auxiliary variableiin order to access the containerarr. The first, range-based loop does not expose any details of the iteration, but just says “do this and that to each element in the collection”.Since the traditional
forloop is a very general control structure, it can also be used in unusual ways:You can trivially rewrite
for(A; B; C)as a while loop:Edit: I would probably be remiss not to mention the library function template
std::for_eachfrom<algorithm>, which in conjunction with lambdas is a very nice and self-descriptive way to iterate over arbitrary ranges (not just entire containers). It has existed since Day 1, but before lambdas it was a show-stopping pain to use.Update: I thought of something else that might be relevant here: A “foreach” loop generally assumes that you don’t modify the container. A common type of looping that modifies the container requires the traditional
for-loop; as for example in this typicalerasepattern: