Synopsis: | Avoid conversions between booleans and non-boolean types |
Language: | C |
Severity Level: | 6 |
Category: | Conversions |
Description: |
Justification Booleans are only defined in logical context. Using them in arithmetic context or converting them to or from arithmetic types relies on the implementation of booleans, which may change in the future. Example bool enabled = true; int enabled_bit; enabled_bit = enabled; /* WRONG: assigning a bool to an int */ enabled_bit = enabled ? 1 : 0; /* RIGHT */ enabled = enabled_bit; /* WRONG: assigning int to bool */ enabled = (enabled_bit == 1); /* RIGHT */ if (enabled == 0) /* WRONG: using boolean as arithmetic type */ if (!enabled) /* RIGHT */ if (enabled_bit && enabled) /* WRONG: using arithmetic type as boolean */ if ((enabled_bit != 0) && enabled) /* RIGHT */ |