自我比较¶
ID: cpp/comparison-of-identical-expressions
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- readability
- maintainability
Query suites:
- cpp-security-and-quality.qls
将变量与自身进行比较的目的是通常用于检测整数溢出或浮点数 NaN。如果比较操作既不是检测整数溢出,也不是检测浮点数 NaN,那么很可能是编码错误。
建议¶
如果强制转换的目的是检测整数溢出,那么请确保比较操作使用显式强制转换,并且类型与预期类型一致。
示例¶
typedef int T;
bool checkOverflow(T x) {
return (x == (int)x); // Always returns true.
}
比较操作始终为真,因为显式强制转换为 int
没有任何效果。这可能意味着 T
的定义自编写 checkOverflow
以来发生了更改,并且 checkOverflow
现在已过时。