[bool wrapping] Request for warnings on implicit bool to int conversions

mathog mathog@caltech.edu
Wed Mar 28 20:30:00 GMT 2012


On 28-Mar-2012 12:18, Michael Witten wrote:

Wow, that was thorough!

The behavior of b++ vs. b-- was interesting, but is yet one more reason 
why the warning is needed.  Since
b-- is equivalent to !b, and b++ is equivalent to 1, if that action is 
intended, there is no reason to
use either the increment or decrement operators on a bool.

>   gcc -std=c99 -pedantic -Wall -O0 -fdump-tree-gimple d.c

That's a trick worth knowing. Thanks!
Ran that on a test program and in every case but one there was an 
implicit

    (int) b

on sections of code which I though should generate warnings.  (Math ops 
on bools, comparison operations of
bool with ints.) The one exception in that little program was:

   b=2;

which came out as

   b=1;

In that case the compiler must have performed an implicit

   1 = (bool) 2

Also these forms all generated implicit int conversions

   if(b==1)
   if(b==2)
   if(b==0)

whereas

   if(b)

did not.

So let's turn this around.  If the compiler warned on all implicit 
conversions of bool <-> int,
what program lines would it warn on that it shouldn't?  It would warn 
on:

   if(b==1)
   if(b==0)

but I would argue that line is inappropriate for a bool type, and 
should be written as:

   if(b)

With two bool variables, this also did not generate an implicit 
conversion (and so would not warn,
which is appropriate):

   if(b1 || b2)

Whereas this less preferred form would have generated an implicit (int) 
[and a well deserved warning]

   if(b1 + b2)

Regards,

David Mathog
mathog@caltech.edu
Manager, Sequence Analysis Facility, Biology Division, Caltech



More information about the Gcc mailing list