https://gcc.gnu.org/bugzilla/show_bug.cgi?id=125081
--- Comment #3 from GCC Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Jakub Jelinek <[email protected]>: https://gcc.gnu.org/g:ed9d0ebe4ecb14e293f40e395657dd08c089ad10 commit r17-521-ged9d0ebe4ecb14e293f40e395657dd08c089ad10 Author: Jakub Jelinek <[email protected]> Date: Fri May 15 08:40:34 2026 +0200 c, c++: Introduce -Wconstant-logical-operand warning [PR125081] Given the recent (data->flags && ff_genericize) vs. (data->flags & ff_genericize) typo, I've looked at warning in similar cases. We don't warn for cases like that at all, clang/clang++ has -Wconstant-logical-operand warning enabled by default. Their behavior is: 1) only warns for rhs of &&/|| (why?) 2) don't warn if rhs is bool 3) for C++ warn if rhs is constant or folds into constant, for C warn if rhs is constant or folds into constant and that constant is not 0 or 1 4) I think it doesn't warn if rhs comes from a macro The following patch implements similar warning with similar wording, just provides the value of the constant, but 1) warns for lhs and rhs 2) doesn't warn if either lhs or rhs is bool 3) doesn't warn if lhs or rhs is or folds to constant 0 or 1 (but does warn if it is constant 1 of enum type in an enum which has enumerator other than just 0/1 (i.e. poor man's boolean)) 4) doesn't care if it comes from a macro or not I think 64 && x is similarly suspicious to x && 64 and both are likely to be meant 64 & x or x & 64. I think having && 1 or && 0 is common even in C++, people don't always write && true or && false etc. and don't see why C++ would be different in that from C, I think people sometimes write if (1 #ifdef ABC && ABC #endif #ifdef DEF && DEF #endif && 1) and similar (or similarly with 0/true/false or ||). And the warning is only enabled in -Wall, not by default. 2026-05-15 Jakub Jelinek <[email protected]> PR c++/125081 gcc/ * doc/invoke.texi (Wconstant-logical-operand): Document. gcc/c-family/ * c.opt (Wconstant-logical-operand): New option. * c.opt.urls: Regenerate. gcc/c/ * c-tree.h (parser_build_binary_op): Add ORIG_ARG1 argument. * c-typeck.cc (parser_build_binary_op): Likewise. Emit -Wconstant-logical-operand warnings. * c-parser.cc (c_parser_binary_expression): Adjust parser_build_binary_op caller, pass to it the original stack[sp - 1].expr.value before c_objc_common_truthvalue_conversion. gcc/cp/ * typeck.cc (cp_build_binary_op): Emit -Wconstant-logical-operand warnings. gcc/testsuite/ * c-c++-common/Wconstant-logical-operand-1.c: New test. * c-c++-common/Wconstant-logical-operand-2.c: New test. Reviewed-by: Jason Merrill <[email protected]> Reviewed-by: "Joseph S. Myers" <[email protected]>
