Re: bool to size_t warning

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 





On 27/08/2019 14:55, Jonathan Wakely wrote:
On Tue, 27 Aug 2019 at 14:48, Jonny Grant <jg@xxxxxxxx> wrote:



On 27/08/2019 13:42, Jonathan Wakely wrote:
On Fri, 9 Aug 2019 at 21:32, Jonny Grant wrote:

Hi
Looks like the bool can't be converted to size_t

Of course it can. You're using options which enable some noisy
warnings and then turn those warnings into errors. But your example
doesn't try to conbert bool to size_t anyway, it performs arithmetic
on bools, which produces an int, then tries to convert that to size_t.
Obviously converting int to size_t changes from signed to unsigned,
and that's why you get a -Wsign-conversion diagnostic.

Questionable code (like performing arithmetic on bool values) will
often trigger noisy warnings that have many false positives. There's a
reason -Wsign-conversion isn't included in -Wall or -Wextra.

It's easy to avoid the warning if you really need to perform arithmetic on bool:

size_t i = size_t(a + b);

or:

size_t i = size_t(a) + b;

I see. I had been expected the bool to be treated as an unsigned number,

It *is* treated as an unsigned number. But C and C++ have a rule
called integer promotion which affects this. Operands smaller than
'int' will be promoted to 'int', so adding two bools is equivalent to
int(a) + int(b). Obviously that is a signed type now.

See https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion

Ok, I see. Thank you for the link.
Jonny



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux