4

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 :(

5
  • 2
    cplusplus.com/reference/algorithm/for_each - use STL containers instead of arrays and you do have it. Commented Nov 14, 2011 at 1:34
  • 1
    @BrianRoach Actually, you don't even have to use an STL container in the latest standard. You can use std::begin() and std::end() in the std::for_each function. Commented Nov 14, 2011 at 1:36
  • Qt (a popular cross-platform C++ toolkit) provides a foreach construct. Commented Nov 14, 2011 at 1:36
  • @MichaelPrice - Yeah ... I'm kinda mixed on whether to start answering C++ questions with C++11 answers. Same thing with Java 7. I suppose offering it as an additional alternative is responsible. Commented Nov 14, 2011 at 1:39
  • @BrianRoach While this is more meta, I'd prefer deprecating the C++11 tag in favor of adding a C++ 98/03 tag that is reserved for questions specific to that version. The same goes for answers. If only those darn compilers would implement the full standard. Commented Nov 14, 2011 at 1:43

6 Answers 6

7

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 for loop 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:

int arr[5] = { 1, 3, 5, 2, 4 };

for (int & n : arr) { n *= 2; } // "for-each" loop, new in C++11

for (size_t i = 0; i != 5; ++i) { arr[i] *= 2; } // "classic" for loop

In the second for, we use a traditional for loop to increment an auxiliary variable i in order to access the container arr. 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 for loop is a very general control structure, it can also be used in unusual ways:

std::vector<std::string> all_lines;
for (std::string line; std::cin >> line; all_lines.push_back(line))
{
  std::cout << "On line " << (all_lines.size() + 1) << " you said: " << line << std::endl;
}

You can trivially rewrite for(A; B; C) as a while loop:

{  // scope!
  A;
  while (true && B)
  {
    {  // more scope!
      /* for loop body */
    }
    C;
  }
}

Edit: I would probably be remiss not to mention the library function template std::for_each from <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 typical erase pattern:

for(Container::const_iterator it = v.begin(); it != v.end() /* not hoisted! */; /* no increment */ )
{
  // do something
  if (suitable_condition)
  {
    v.erase(it++);   // or it = v.erase(it), depending on container type
  }
  else
  {
    ++it;
  }
}
Sign up to request clarification or add additional context in comments.

11 Comments

So really I can use them interchangeably but can possibly do more with a for loop?
@Howdy_McGee: Yes. I added an unusual for example. The standard for loop really is just short for, "a) initialize some stuff; b) if some condition holds, do some stuff; c) perform some operation; d) goto b)".
@Howdy_McGee: It might help you to think of a for loop as a convenient while loop. I added that explanation.
Thanks, I understand the for loop but why do other languages need a foreach if a for can do the same thing and then some ya know
@Howdy_McGee: It's all about expression of intent. If you have a container, the for-each (or ranged-for, in C++) loop lets you express that you want to access container elements, nothing more and nothing less. Note how the range-based loop has a much simpler body, since no unnecessary information is exposed. Programming is all about expressing a mental model, and having an idiomatic construction available helps to make your code clearer and more self-explanatory.
|
1

foreach generally has 1 parameter, for has 3. Anything foreach can do for can too. Part of the reason why foreach doesn't exist in C++ is because the number of iterations can't always be inferred from the type.

I believe boost library has a method of getting foreach to work, and C++11 has a range-based of for:

int my_array[5] = {1, 2, 3, 4, 5};
for (int &x : my_array) {
    x *= 2;
}

Comments

1

There is something like for each for arrays in C++ and that is iterators. Both loops are essentially identical with the only difference being - with an ordinary for loop you have an index which you might need depending on what type of data you are accessing and whether you need to do some calculations with the index and there is (probably) an increased chance of off-by-one errors. Whereas foreach loops just guarantee that will be executed as many times as there are elements in the array without exposing an index (which you can mimic) so as a I said they are essentially the same but their usage largely depends on the way you manipulate your data.

Comments

0

"For Each" syntax is used to iterate through a collection of objects, while a for loop is a loop that will execute for a given range. C++ does have for_each in its STL and can be used to iterate through linear object containers such as a vector.

2 Comments

A for loop has nothing to do with "ranges". It's about checking conditionals and executing statements.
Technically you are correct, but when compared to for_each range is appropriate. I'd even stake the claim that most for loop conditions written are based on some type of range, and generally iterate through some type of indexed data. Using a for loop to test boolean "conditionals" is inappropriate when you have do and while loops available.
0

In other languages with a foreach construct, they're usually convenience for not having to index into the collection you're looping over. That is, you're given the next object in the collection without having access to (or need for) the index itself. If you need the index for some reason, you'll usually need the for loop, though in some languages you have access to the counter in their 'foreach'.

Comments

0

as experience test , FOR is more Faster than FOREACH

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.