|
1 | 1 | # bitwiseOnBoolean |
2 | 2 |
|
3 | 3 | **Message**: Boolean expression 'x' is used in bitwise operation. Did you mean '&&'?<br/> |
4 | | -**Category**: Code Quality<br/> |
| 4 | +**Category**: Readability<br/> |
5 | 5 | **Severity**: Style (Inconclusive)<br/> |
6 | 6 | **Language**: C/C++ (also applies to C's `_Bool`) |
7 | 7 |
|
|
11 | 11 |
|
12 | 12 | ## Motivation |
13 | 13 |
|
14 | | -`&`/`|` and `&&`/`||` look similar but behave very differently: the bitwise operators always evaluate |
15 | | -both sides (no short-circuiting) and, for non-`bool` operands, work bit-by-bit rather than on the |
16 | | -boolean truth value - so a stray single `&`/`|` where `&&`/`||` was meant can silently change behaviour. |
| 14 | +This checker is about readability. Readability is subjective - opinions differ about what is more |
| 15 | +readable. Please follow your own opinion. |
| 16 | + |
| 17 | +When both operands are `bool`, `&`/`|` on their `0`/`1` representation happens to produce the same |
| 18 | +truth value as `&&`/`||`, so this code usually still works correctly today. The main reason to flag it |
| 19 | +anyway is common practice: `&&`/`||` is the conventional, unambiguous way to write boolean logic in |
| 20 | +C/C++, while `&`/`|` is understood to mean bitwise work - so a stray single `&`/`|` reads as a likely |
| 21 | +typo even when it happens to be harmless. There is also one real behavioural difference: `&`/`|` always |
| 22 | +evaluates both operands, so if the other side has a side effect, using `&`/`|` instead of `&&`/`||` |
| 23 | +changes whether that side effect happens. |
| 24 | + |
| 25 | +When the *other* operand isn't itself boolean (e.g. an integer flag or count), `&`/`|` combines the |
| 26 | +boolean's `0`/`1` value with it bit-by-bit, which generally is **not** the same truth value `&&`/`||` |
| 27 | +would produce - in that case this points at an actual logic bug, not just a style preference. |
17 | 28 |
|
18 | 29 | ## How to fix |
19 | 30 |
|
|
0 commit comments