Boost logo

Boost :

Subject: Re: [boost] Current Guidance on Compiler Warnings?
From: Gavin Lambert (boost_at_[hidden])
Date: 2018-11-28 02:47:35


On 28/11/2018 13:56, Emil Dotchevski wrote:
>> As should hopefully be obvious, implicit narrowing conversions are never
>> a good idea.
>
> short f();
>
> short x = f();
> short y = x+1; //Implicit conversion from int to short.
>
> Do you think the compiler should warn in this case? Is the version below
> better? Safer?
>
> short y = static_cast<short>(x+1);

No, that's a language defect. In that context "1" should be of type
short (because as a literal, it can be) and then it should apply "short
operator+(short, short)", and then there would be no problem (assuming
it doesn't overflow).

(Or as a general rule, the literal "1" should actually be type int8_t,
because that's the smallest signed type which includes its value, and
can always be safely implicitly extended to a larger type based on usage.)

I am aware that the language does not work like this currently. This is
one of the things that make it so easy to produce incorrect code.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk