r/C_Programming • u/aartaka • Sep 21 '26
Question Warn on bool x = 1/0?
Hi y’all. It’s me waging war against sloppy types again. This time I want to make sure that ints are not assigned to bool fields and variables. Is there some compiler flag on GCC and/or Clang that detects when this happens? I tried
-Wbool-compare-Wbool-operation- Compiling with
g++instead ofgcc
No warnings shown on assigning 0/1 to a boolean field. Is there a way to warn on that?
11
Upvotes
2
u/WittyStick Sep 22 '26
There's a
--Wint-in-bool-contextwhich will detect some cases, such as where you use integers inif/whilecondition.boolitself is an integer type though, which just accepts0as false and nonzero astrue.With GCC you can use a different value for true and false with the
hardboolattribute. Eg, you can make0xFFbefalseand0x00..0xFEbetrue.25
u/FancySpaceGoat Sep 21 '26 edited Sep 21 '26
The type of comparison expressions is
int.So by your rule
bool some_bool = v > 10;would warn, which is obviously undesirable.You may be tempted to think that this can be special-cased away. But since type inference is a thing, we need to also allow initializing from an
intvariable:And at that point warning on
bool some_bool = 1;just seems silly.All this to say that doing this right goes beyond the scope of what a compiler could/should be doing as part of its warnings. This is more of a job for a dedicated static analyzer tool like clang-tidy.
7
u/_thetek_ Sep 21 '26
IIRC, clang-tidy might have a diagnostic for that.
2
u/pfp-disciple Sep 21 '26
Would
-Wfloat-conversiongive you what you need? It's a subset of-Wconversion0
u/[deleted] Sep 21 '26
[deleted] — view deleted comment