GeneralPurpose-CouldBeRangeBasedLoop

A for-loop that loops through all elements of the container and does not use its loop-counter other than to index a container could be a range-based loop

Required inputs: IR

Range-based for loops are clearer, safer, and less error-prone than traditional index-based loops when iterating through all elements of a container. This rule detects traditional for loops that iterate through a container using a loop counter but never use the counter except to index the container. These loops can be simplified to range-based for loops.
Bad code (traditional loop that could be range-based):
std::vector<int> values = {1, 2, 3, 4, 5};

// Loop counter only used for indexing
for (int i = 0; i < values.size(); ++i) {
    std::cout << values[i];  // Could use range-based loop
}
Good code (range-based for loop):
std::vector<int> values = {1, 2, 3, 4, 5};

// Clearer intent, no index management needed
for (int value : values) {
    std::cout << value;
}
Exception (counter used for other purposes):
std::vector<int> values = {1, 2, 3, 4, 5};

// Loop counter used for more than indexing - keep traditional loop
for (int i = 0; i < values.size(); ++i) {
    std::cout << "Value " << i << ": " << values[i];  // i used for output
}

Possible Messages

Key

Text

Severity

Disabled

could_be_range_based

For loop could be a range-based for loop.

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

An enumeration.
 
  • misra_c_2004

  • misra_c_2004_continue

  • misra_c_2012

  • misra_c_2012_continue

  • misra_cpp_2008

  • cert

  • generic