AutosarC++17_10-A6.5.2

A for loop shall contain a single loop-counter which shall not have floating-point type

Required inputs: IR

Rationale

A for loop without a loop-counter is simply a while loop. If this is the desired behavior, then a while loop is more appropriate.

Floating types, as they should not be tested for equality/inequality, are not to be used as loop-counters.

Example
// $Id: A6-5-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
namespace {
constexpr std::int32_t xlimit = 20;
constexpr std::int32_t ylimit = 15;
constexpr float zlimit = 2.5F;
constexpr std::int32_t ilimit = 100;
} // namespace
void Fn() noexcept {
  std::int32_t y = 0;

  for (std::int32_t x = 0; x < xlimit && y < ylimit;
       x++, y++) // Non-compliant, two loop-counters
  {
    // ...
  }

  for (float z = 0.0F; z != zlimit; z += 0.1F) // Non-compliant, float with !=
  {
    // ...
  }

  for (float z = 0.0F; z < zlimit; z += 0.1F) // Non-compliant, float with <
  {
    // ...
  }

  for (std::int32_t i = 0; i < ilimit; ++i) // Compliant
  {
    // ...
  }
}
See Also
  • MISRA C++ 2008 [6]: Rule 6-5-1 A for loop shall contain a single loop-counter which shall not have floating type.
  • C++ Core Guidelines [10]: ES.72: Prefer a for-statement to a while-statement when there is an obvious loop variable.

Possible Messages

Key

Text

Severity

Disabled

loop_float_counter

Loop-counter of for loop shall not have floating type

None

False

loop_missing_counter

For loop has no loop-counter

None

False

loop_multiple_counters

For loop shall have only a single loop-counter

None

False

Options

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