bool to size_t warning

Maksim Fomin maxim@fomin.one
Fri Aug 9 20:55:00 GMT 2019


‐‐‐‐‐‐‐ 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.



More information about the Gcc-help mailing list