← back to index

S127 — "for" loop stop conditions should be invariant

Language: C#  |  Type: CODE_SMELL  |  Severity: Major

Tags: pitfall

Why is this an issue?

A for loop stop condition should test the loop counter against an invariant value, one that is true at both the beginning and ending of every loop iteration. Ideally, this means that the stop condition is set to a local variable just before the loop begins.

This rule tracks when incremented counters used in the stop condition are updated in the body of the for loop.

What is the potential impact?

Non-invariant stop conditions can lead to unexpected loop behavior, making the code harder to debug and maintain. If the stop condition changes unexpectedly during iteration, it may cause:

How to fix it

It is generally recommended to only update the loop counter in the loop declaration. If skipping elements or iterating at a different pace based on a condition is needed, consider using a while loop or a different structure that better fits the needs.

Code examples

Noncompliant code example

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
    if (condition)
    {
        i = 20;
    }
}

Compliant solution

int i = 1;
while (i <= 5)
{
    Console.WriteLine(i);
    if (condition)
    {
        i = 20;
    }
    else
    {
        i++;
    }
}

How does this work?

A while loop signals that the iteration logic may be more complex, so readers will naturally look for control flow changes within the loop body. This makes the code’s intent clearer and easier to reason about.