Rule A6-5-1 (required, implementation, automated)
A for-loop that loops through all elements of the container and does not use its loop-counter shall not be used.
Rationale
A for-loop that simply loops through all elements of the container and does not use its loop-counter is equivalent to a range-based for statement that reduces the amount of code to maintain correct loop semantics.
Example
// $Id: A6-5-1.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
#include <iterator>
void Fn() noexcept
{
constexpr std::int8_t arraySize = 7;
std::uint32_t array[arraySize] = {0, 1, 2, 3, 4, 5, 6};
for (std::int8_t idx = 0; idx < arraySize; ++idx) // Compliant
{
array[idx] = idx;
}
for (std::int8_t idx = 0; idx < arraySize / 2;
++idx) // Compliant - for does not loop though all elements
{
// ...
}
for (std::uint32_t* iter = std::begin(array); iter != std::end(array);
++iter) // Non-compliant
{
// ...
}
for (std::int8_t idx = 0; idx < arraySize; ++idx) // Non-compliant
{
// ...
}
for (std::uint32_t value :
array) // Compliant - equivalent to non-compliant loops above
{
// ...
}
for (std::int8_t idx = 0; idx < arraySize; ++idx) // Compliant
{
if ((idx % 2) == 0)
{
// ...
}
}
}
See also
HIC++ v4.0 [9]: 6.2.1 Implement a loop that only uses element values as a range-based loop. C++ Core Guidelines [11]: ES.55: Avoid the need for range checking. C++ Core Guidelines [11]: ES.71: Prefer a range-for-statement to a forstatement when there is a choice.