Re: bool to size_t warning

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

 





On 09/08/2019 21:55, Maksim Fomin wrote:
‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Friday, August 9, 2019 8:32 PM, Jonny Grant <jg@xxxxxxxx> 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.
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