Non-boolean value implicitly converted to bool
ID |
c.maintainability.implicit_bool_conversion |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Type Safety |
Language |
C / C++ |
Description
A non-boolean value is stored into a bool without an explicit comparison. The compiler silently converts any nonzero value to true and zero to false, which hides the actual condition being tested and can surprise a reader who expects the source to already be boolean. Compare the value against the meaningful threshold explicitly, e.g. code != 0.
Rationale
A non-boolean value is stored into a bool without an explicit comparison. The compiler silently converts any nonzero value to true and zero to false, which hides the actual condition being tested and can surprise a reader who expects the source to already be boolean. Compare the value against the meaningful threshold explicitly, e.g. code != 0.
The following code illustrates the pattern detected by this rule:
bool checkStatus(int code, bool ready, bool *out)
{
// FLAGGED: Non-boolean value implicitly converted to bool
bool ok = code;
// FLAGGED: Non-boolean value implicitly converted to bool
ok = code;
bool positive = code > 0;
bool same = ready;
bool literalTrue = true;
positive = (code > 0);
ok = ready && positive;
*out = ok;
return ok;
}