Search code examples
programming-languagesloopsfor-loop

Why do some programming languages restrict you from editing the array you're looping through?


Pseudo-code:

for each x in someArray {
    // possibly add an element to someArray
}

I forget the name of the exception this throws in some languages.

I'm curious to know why some languages prohibit this use case, whereas other languages allow it. Are the allowing languages unsafe -- open to some pitfall? Or are the prohibiting languages simply being overly cautious, or perhaps lazy (they could have implemented the language to gracefully handle this case, but simply didn't bother).

Thanks!


Solution

  • What would you want the behavior to be?

    list = [1,2,3,4]
    foreach x in list:
        print x
        if x == 2: list.remove(1)
    

    possible behaviors:

    list is some linked-list type iterator, where deletions don't affect your current iterator:

    [1,2,3,4]
    

    list is some array, where your iterator iterates via pointer increment:

    [1,2,4] 
    

    same as before, only the system tries to cache the iteration count

    [1,2,4,<segfault>]
    

    The problem is that different collections implementing this enumerable/sequence interface that allows for foreach-looping have different behaviors.