Start learning free

LESSON 142 OF 667 · FOR LOOPS - LOOPING OVER ARRAYS

Infinite For Loops II in C++

Lesson

We also use for loops to iterate over sequences like strings and arrays. We can run into problems when we manipulate a sequence while iterating on it.

For example, if we append elements to a vector while iterating on it:

vector<string> fruits = {"banana", "orange"};

for (auto fruit : fruits) {
  fruits.push_back("kivi");
}

Every time we enter this loop, we add a kivi item to the end of the vector that we are iterating through, so we would never make it to the end of the vector.

In C++ this is even worse than an infinite loop: it is undefined behavior. The range-based for loop holds iterators into the vector, and push_back may move the elements to a bigger block of memory, which leaves those iterators pointing at memory that was freed. The program might stop after the original items, print garbage, run forever or crash.

Changing a collection while looping over it is always a bug. And when nothing stops the loop, the collection keeps growing forever: an infinite loop. As programmers, we want to make sure we never write infinite loops, as they make our program run forever and completely unusable.


Assignment
Follow the Coding Tutorial and let's practice with infinite for loops!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check