AutosarC++18_03-A6.5.1

A for-loop that loops through all elements of the container and does not use its loop-counter shall not be used

Required inputs: IR

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 [8]: 6.2.1 Implement a loop that only uses element values as a range- based loop.
  • C++ Core Guidelines [10]: ES.55: Avoid the need for range checking.
  • C++ Core Guidelines [10]: ES.71: Prefer a range-for-statement to a for-statement when there is a choice.

Possible Messages

Key

Text

Severity

Disabled

could_be_range_based

For loop could be a range-based for loop.

None

False

unused_loop_counter

For loop does not use its loop counter.

None

False

Options

exclude_simple_for_loops

exclude_simple_for_loops : bool = True

If set to true, this rule will not report unused loop counters in the simple cases where the C for-loop only references loop-counters in its condition but no other variables.
 

loop_counter_model

loop_counter_model

Type: LoopCounterModel

Default: 'misra_cpp_2008'

The loop counter model on which the analysis is based.
 

Option Types

These types are used by options listed above:

LoopCounterModel

  • misra_c_2004

  • misra_c_2004_continue

  • misra_c_2012

  • misra_c_2012_continue

  • misra_cpp_2008

  • cert

  • generic