ModifiedControlVariable

Since Checkstyle 3.5

Description

Checks that for loop control variables are not modified inside the for block. An example is:
for (int i = 0; i < 1; i++) {
  i++; // violation
}
        

Rationale: If the control variable is modified inside the loop body, the program flow becomes more difficult to follow. See FOR statement specification for more details.

Such loop would be suppressed:

for (int i = 0; i < 10;) {
  i++;
}
        

NOTE:The check works with only primitive type variables. The check will not work for arrays used as control variable.An example is

for (int a[]={0};a[0] < 10;a[0]++) {
 a[0]++;   // it will skip this violation
}
        

Properties

name description type default value since
skipEnhancedForLoopVariable Control whether to check enhanced for-loop variable. boolean false 6.8

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="ModifiedControlVariable"/>
  </module>
</module>
        

Example:

class Example1 {
  void InvalidExample() {
    for(int i=0;i < 8;i++) {
      i++; // violation, control variable modified
    }
    String args1[]={"Coding", "block"};
    for (String arg: args1) {
      arg = arg.trim(); // violation, control variable modified
    }
  }
}
        

By default, This Check validates Enhanced For-Loop.

Option 'skipEnhancedForLoopVariable' could be used to skip check of variable from Enhanced For Loop.

An example of how to configure the check so that it skips enhanced For Loop Variable is:

<module name="Checker">
  <module name="TreeWalker">
    <module name="ModifiedControlVariable">
      <property name="skipEnhancedForLoopVariable" value="true"/>
    </module>
  </module>
</module>
        

Example:

class Example2 {
  void InvalidExample() {
    for(int i=0;i < 8;i++) {
      i++; // violation, control variable modified
    }
    String args1[]={"Coding", "block"};
    for (String arg: args1) {
      arg = arg.trim();
    }
  }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker