Avoid equality in loop termination condition

Why you should care

Testing for loop termination using an equality operator (== and !=) is dangerous, because it could set up an infinite loop. Using a broader relational operator instead casts a wider net, and makes it harder (but not impossible) to accidentally write an infinite loop.

How we detect

CAST Highlight counts one occurrence each time a loop (for or while) use an equality in its termination condition, except for comparisons to NULL.

An equality is an expression using an operator == or !=

Bad Code 

for (int i = 1; i != 10; i += 1) {
  //...
}
while (i != 10) {
  //...
}

Good Code 

for (int i = 1; i < 10; i += 1) {
  //...
}
while (i != null) {
  //...
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.