CodeQL 文档

比较结果始终相同

ID: cpp/constant-comparison
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - maintainability
   - readability
Query suites:
   - cpp-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

如果 xy 的范围不重叠,则像 x >= yx != y 这样的比较操作将始终返回相同的结果。在某些情况下,这会导致无限循环。在下面的示例中,第 9 行的循环条件始终为真,因为 i 的范围是 [0..5],因此循环永远不会终止。

为比较运算符的左右操作数推断出的边界包含在消息中,因为它们通常可以更容易地理解为什么报告了结果。例如,对于比较 x >= y 的消息可能显示为:“比较始终为假,因为 x >= 5 且 3 >= y。”

建议

检查表达式,看是否需要不同的语义。

示例

int f() {
  int i;
  int total = 0;

  for (i = 0; i < 10; i = i+1) {  // GOOD: comparison could be either true or false.
    total += i;
  }

  for (i = 0; i < 10; i = i+1) {  // BAD: comparison is always true, because i <= 5. 
    i = i % 5;
    total += i;
  }

  return total;
}

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私