-5
$\begingroup$

When iterating over an array you can use an indexed for loop, like so:

for (int i = 0; i < vectorSize; i++) {
    e = element i of array
    use e for something
}

but you can also use a loop that goes through each item in the array without using an index:

for (auto e : vector) {
    use e for something
}

I've noticed that some languages support both types of loops, while some only use one or the other. What are the pros and cons of implementing the 'indexed' for loop as opposed to implementing a for-each loop?

$\endgroup$
4
  • 5
    $\begingroup$ This is more of best practices than language design, no? $\endgroup$ May 17, 2023 at 7:29
  • $\begingroup$ True, but there are other questions based on 'best practices' that are similar and I think it is on-topic. $\endgroup$
    – Redz
    May 17, 2023 at 7:31
  • 1
    $\begingroup$ Would that make it a duplicate of my question? Would still be closed, just for a different reason $\endgroup$
    – Bbrk24
    May 19, 2023 at 0:20
  • $\begingroup$ That's true, I just realized... but I would still rather have it closed as duplicate than off-topic and have the answers be linked $\endgroup$
    – Redz
    May 19, 2023 at 0:21

1 Answer 1

3
$\begingroup$

Obviously the indexed loop is more flexible in how it can update the index. Depending on the rest of the language this can matter more or less. Consider things like:

  1. Iterating from the back.
  2. Stepping every second or third index.
  3. Skipping a variable amount of steps due to some data condition.
  4. Removing entries during the loop.
  5. Adding entries during the loop.
  6. Storing the index where the loop terminated (if exiting using a break or similar)
  7. Tracking the index.

The above points may or may not be supported by foreach as well, but it gives examples of why an index may sometimes be more useful.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged .