Boost logo

Boost :

Subject: Re: [boost] Current Guidance on Compiler Warnings?
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2018-11-28 03:28:43


On Tue, Nov 27, 2018 at 6:47 PM Gavin Lambert via Boost <
boost_at_[hidden]> wrote:
>
> 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).

Your position is self-contradictory. You're saying that under short
operator+(short,short), it's fine to assume no overflow, without a warning,
even though short overflow would produce incorrect y, but under int
operator+(short,short) it's not fine to truncate the int result to short,
without a warning, even though it would produce (on most platforms, exactly
the same) incorrect y.

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

The language currently works correctly in this case, thanks god. The idea
that if x and y are of type short, then x+y should be of type short is
utterly wrong. When you add two shorts, you get an int, because computing
the int result does not use more resources than computing the short result.
And, of course, it should be truncated when stored in a short. And, of
course, it would be lame to warn about the potential loss of data. It's
just x+1, it's not that dangerous. :)


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