ProgrammingHardProduct-company placement · C++

What is wrong with this loop?

What is wrong with this loop?
vector<int> v{1, 2, 3};
for (int x : v)
    if (x == 1) v.push_back(1);
  1. A. Nothing; the loop runs over the original 3 elements only
  2. B. It loops forever because a 1 is always appended
  3. C. It fails to compile because v is modified inside a range-for
  4. D. push_back may reallocate the vector, invalidating the range-for's iterators: undefined behaviour

Correct answer: D. push_back may reallocate the vector, invalidating the range-for's iterators: undefined behaviour

A range-for holds begin/end iterators; growing the vector can move its storage and invalidate them, so continuing the loop is undefined behaviour.

More OOP with C++ and Java questions

Exams that ask this topic