Why does deleting array elements in a forward Для loop break?
The procedure must remove every zero from the array Остатки passed to it. Called with an array of 0, 0, 5, it ends with an error.
Constraints: change the caller's array itself and keep the order of the remaining elements.
Процедура УдалитьНулевые(Остатки)
Для Индекс = 0 По Остатки.ВГраница() Цикл
Если Остатки[Индекс] = 0 Тогда
Остатки.Удалить(Индекс);
КонецЕсли;
КонецЦикла;
КонецПроцедурыFind and fix the bug.
Nothing needs to be imported: all the code goes in this module.
Удалить shifts the later elements one place left, so the loop skips the element that moved into the current index, and the bound computed once at the start runs past the shrunk array. Walk from ВГраница() down to 0 instead.
- Expecting the loop to see each element once after
Удалить: the remaining elements shift and one is skipped - Thinking the
Поbound is re-read on every pass: it is computed once when the loop starts
- How would you remove the zeros without changing the caller's array?
- Why is deleting elements inside
Для Каждогоover the same array also unsafe?
After Удалить(Индекс) the next element moves into the deleted one's place, and the loop, stepping to Индекс + 1, skips it. The bound Остатки.ВГраница() is computed once when the loop starts, so the last indexes no longer exist and reading Остатки[Индекс] fails with an index-out-of-range error. Walking from the end, a deletion shifts only the elements already checked:
Процедура УдалитьНулевые(Остатки)
Индекс = Остатки.ВГраница();
Пока Индекс >= 0 Цикл
Если Остатки[Индекс] = 0 Тогда
Остатки.Удалить(Индекс);
КонецЕсли;
Индекс = Индекс - 1;
КонецЦикла;
КонецПроцедурыFor an empty array ВГраница() returns −1, and the loop never runs.