[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects
Arthur O'Dwyer via Phabricator via cfe-commits
cfe-commits at lists.llvm.org
Mon Aug 16 16:50:30 PDT 2021
Quuxplusone added a comment.
> Can we either emit that [`a &= foo()`] as a suggestion if the code looks like `a = a & foo()`? Or simply not emit a warning?
The problem is that if `a` is boolean, then `a = a & something` is 99% for sure a typo — 99% of the time, the programmer meant `a = a && something`. So any compiler suggestion or fixit that blindly "doubles down" on the non-short-circuiting behavior is a bad idea. https://quuxplusone.github.io/blog/2020/09/02/wparentheses/ is relevant.
One proper way to silence the warning //without// short-circuiting would be `a = int(a) & something` — this indicates that you really do want integer bitwise-ANDing, not boolean. Alternatively, and probably best, just declare `a` as an integer variable to begin with. Of course the compiler cannot recommend this if `something` isn't strictly zero or one. But in that case you might already have a bug:
int error_returning_func() { return 2; }
int main() {
bool t = true;
t = t && error_returning_func();
assert(t); // still true
t = t & error_returning_func();
assert(!t); // now it's false
}
So typo'ing `&` for `&&` doesn't just turn off short-circuiting — it can also mess up the runtime value stored in the bool.
CHANGES SINCE LAST ACTION
https://reviews.llvm.org/D108003/new/
https://reviews.llvm.org/D108003
More information about the cfe-commits
mailing list