Use `while` for infinite loops
See original GitHub issueI would like to propose the implementation and inclusion of a new StyleCop diagnostic.
Category: Readability
Rule: Use while for infinite loops
Description: Infinite loops can be expressed as either while (true)
or for (;;)
. The former should always be used.
Background: Some older compilers, especially older non-optimizing C++ compilers or script compilers, produced sub-optimal code for a while (true)
- e.g. they would emit code to evaluate the expression true
followed by a conditional branch instruction. These same compilers would recognize the empty increment and condition blocks of a for (;;)
statement, and emit an optimized unconditional branch instruction without any other evaluation. As a result, many highly-experienced developers who previously worked with these compilers have a habit of writing for (;;)
in code. Developers coming from most other backgrounds tend to write while (true)
instead.
Rationale: The C# compiler does not impose technical or performance limitations that restrict our ability to make a decision on this matter. As such, I believe that the decision should be made based on what the majority of C# developers would find easiest to read. I also believe this is while (true)
.
Analysis: There are several ways this could be implemented which impact the overall scope.
- This could be limited to locating specific cases of
for(;;)
. - This could be limited to locating cases of
for(;{expression}?;)
. - This could be limited to locating cases of any
for
statement which does not have an increment expression (the initializer, if any, could be placed before thewhile
statement when converting to it). This introduces an additional challenge for a code fix because changing an initializer expression to a variable declaration statement changes the scope of a variable, and would need to handle any conflicts which arose.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:1
- Comments:6 (3 by maintainers)
I’ve always written an infinite loop as
for (;;)
just because it’s slightly more concise than thewhile (true)
equivalent; I hadn’t realised this was unusual. For completeness, it’s worth noting that StyleCopAnalyzers raise a violation of SA1002 when you do this, which the original version never did.I’ve raised https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1489 for discussion of that.
Us old C hacks are used to for(;😉, but I think while(true) is easier to understand. I think 3 is the right choice. The code fix can change
to
but if foo would cause a conflict, then wrap the whole thing in another set of braces. Presumably, since this is ugly, the programmer would then change the variable name. So the code fix would do this only in cases of conflict. This:
would turn into this:
The other alternative is to have the code fix refuse to operate if it would cause a problem.