赋值运算符误用为比较运算符¶
ID: cpp/assign-where-compare-meant
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- reliability
- correctness
- external/cwe/cwe-481
Query suites:
- cpp-security-and-quality.qls
此规则查找赋值运算符 =
的使用情况,在这些情况下使用等号运算符 ==
会更有意义。这是 C 和 C++ 中非常常见的错误,因为 =
和 ==
运算符很相似,并且 if
语句接受具有整型类型的条件,而不是将其限制为仅 bool
类型。
该规则会标记每个在将结果解释为真值的位置出现的赋值运算符。只有当赋值运算符的右侧为编译时常量时,才会标记该赋值运算符。
建议¶
检查以确保标记的表达式不是拼写错误。如果确实需要将赋值运算符作为真值处理,最好用括号将其括起来。
示例¶
if(p = NULL) { //most likely == was intended. Otherwise it evaluates to the value
//of the rhs of the assignment (which is NULL)
...
}
参考资料¶
Tutorialspoint - C++ 编程语言:C++ 中的运算符
维基百科:C 和 C++ 中的运算符
常见弱点枚举:CWE-481.