S1264 replace `for` with `while` false positive

  • Operating system: Win 10-64
  • SonarLint plugin version: 7.2.0.76209
  • Programming language you’re coding in: C# .Net 8
  • Is connected mode used: No

S1264 states that a while loop should be used when only the condition expression is defined in a for loop. This makes sense:

Noncompliant code example

for (;condition;) { /*...*/ }

Compliant solution

while (condition) { /*...*/ }

However, the warning fires when the variable is declared outside of a for loop. While rare, there are cases when one may do this, and no rule states one cannot do so.

Example:

int i;

for (i = 0; i < indexes.Count - 1;)
...

But this can (and therefor should) be written?


int i = 0;

while (i < index.Count - 1)
{
    // ...
}

Seems not as FP to me.

I’m merely pointing out that the case I provided doesn’t align with the rule’s definition.

Hello @IRC,

Sorry for the delay.

Thank you for reporting this inconsistency in the rule description.

I created a ticket to tackle this in the future.

The rule considers anything else than a declaration in the initializer section of the for statement as non-compliant. We will update the rule description to match this requirement.

Have a nice day!

1 Like