bool to size_t warning

Martin Sebor msebor@gmail.com
Wed Aug 28 00:07:00 GMT 2019


On 8/9/19 9:16 PM, Xi Ruoyao wrote:
> On 2019-08-09 22:00 +0100, Jonny Grant wrote:
>>
>> On 09/08/2019 21:55, Maksim Fomin wrote:
>>> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
>>> On Friday, August 9, 2019 8:32 PM, Jonny Grant <jg@jguk.org> wrote:
>>>
>>>> Hi
>>>> Looks like the bool can't be converted to size_t
>>>>
>>>> Seems a shame it can't also convert to size_t
>>>>
>>>> What is strange in the example below, is I change it only a single
>>>> conversion, or as follows, it compiles ok, so there must still be a
>>>> conversion?
>>>>
>>>> Is this an issue worth reporting as a PR?
>>>>
>>>> size_t i = a;
>>>> i += b;
>>>>
>>>> The C spec states |true|which expands to the integer
>>>> constant|1|,|false|which expands to the integer constant|0|
>>>>
>>>> #include<cstddef>
>>>>
>>>> intmain()
>>>> {
>>>> boola = false;
>>>> boolb = true;
>>>> //size_t i = a;
>>>> size_t i = a + b;
>>>>
>>>> returni;
>>>> }
>>>>
>>>> #1 with x86-64 gcc (trunk)
>>>> <source>: In function 'int main()':
>>>>
>>>> <source>:9:18: error: conversion to 'size_t' {aka 'long unsigned int'}
>>>> from 'int' may change the sign of the result [-Werror=sign-conversion]
>>>>
>>>>       9 |     size_t i = a + b;
>>>>
>>>>         |                ^
>>>>
>>>> cc1plus: some warnings being treated as errors
>>>>
>>>> Compiler returned: 1
>>>>
>>>> Please include my email in any replies
>>>> Thanks, Jonny
>>> 1. You mention C language but use C++ compiler: #include<cstddef> and
>>> 'cc1plus'.
>>>
>>> 2. You can find answer in C++ language latest draft (
>>> http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4820.pdf)
>>> [expr.add], [expr.arith.conv], [conv.prom].
>>>
>>> TL;DR '+' promotes bools to signed integer which is not compatible with
>>> size_t' {aka 'long unsigned int'}.
>>>
>>> You can use  size_t i = a + (size_t)b.
>>>
>>
>> Fair enough. It is a shame the C++ spec didn't allow them to be treated
>> as signed, or unsigned, they'll certainly never be negative anyway.
> 
> "signed bool" does not make sense, I think :).
> 
> The problem is that "-Wconversion" and "-Wsigned-conversion" really need some
> improvement.

GCC does manage to avoid these warnings for constants that don't
become negative.  It also has enough information to avoid them in
cases when the promotion is from an unsigned type that's narrower
than int, such as unsigned char or unsigned short.  But it doesn't
consider the original type.  Clang implements the same
-Wsign-conversion warning but it doesn't issue it for this case.
I agree that it would make the GCC warning more useful if it
handled these cases gracefully as well.

I would suggest to open a bug.

Martin



More information about the Gcc-help mailing list