2023-05-03 11:06:20 +02:00
== Why is this an issue?
2020-06-30 10:16:44 +02:00
include::../description.adoc[]
2024-02-27 13:11:19 +01:00
== How to fix it
2020-06-30 10:16:44 +02:00
2024-02-27 13:11:19 +01:00
It's 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
[source,csharp,diff-id=1,diff-type=noncompliant]
2020-06-30 10:16:44 +02:00
----
2024-02-27 13:11:19 +01:00
for (int i = 1; i <= 5; i++)
2020-06-30 10:16:44 +02:00
{
2024-02-27 13:11:19 +01:00
Console.WriteLine(i);
if (condition)
2020-06-30 10:16:44 +02:00
{
2024-02-27 13:11:19 +01:00
i = 20;
2020-06-30 10:16:44 +02:00
}
}
----
2024-02-27 13:11:19 +01:00
==== Compliant solution
2020-06-30 10:16:44 +02:00
2024-02-27 13:11:19 +01:00
[source,csharp,diff-id=1,diff-type=compliant]
2020-06-30 10:16:44 +02:00
----
2024-02-27 13:11:19 +01:00
int i = 1;
while (i <= 5)
2020-06-30 10:16:44 +02:00
{
2024-02-27 13:11:19 +01:00
Console.WriteLine(i);
if (condition)
2020-06-30 10:16:44 +02:00
{
2024-02-27 13:11:19 +01:00
i = 20;
}
else
{
i++;
2020-06-30 10:16:44 +02:00
}
}
----
2021-06-02 20:44:38 +02:00
2024-02-27 13:11:19 +01:00
include::../rspecator.adoc[]