std::string::find result used directly as a boolean condition
ID |
c.correctness.find_result_used_as_boolean |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Suspicious Comparison |
Language |
C / C++ |
Description
std::string::find returns a character position, not a boolean: it returns std::string::npos when the substring is absent and an index (often 0) when it is present at the start. Using the result directly as a condition treats a match at position 0 as false and misclassifies it. Compare the result explicitly against std::string::npos instead.
Rationale
std::string::find returns a character position, not a boolean: it returns std::string::npos when the substring is absent and an index (often 0) when it is present at the start. Using the result directly as a condition treats a match at position 0 as false and misclassifies it. Compare the result explicitly against std::string::npos instead.
The following code illustrates the pattern detected by this rule:
void directCondition(std::string s) {
// FLAGGED: std::string::find result used directly as a boolean condition
if (s.find("needle")) {
doA();
}
}