Boost logo

Boost :

Subject: Re: [boost] Current Guidance on Compiler Warnings?
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2018-11-27 21:01:49


On Mon, Nov 26, 2018 at 9:30 PM Gavin Lambert via Boost <
boost_at_[hidden]> wrote:
> But for the case where you're passing a parameter or other variable of
> the wrong type, it really should have at least the option to generate a
> warning

The problem is that implicit conversions happen a lot in C++ and it is
wrong for the compiler to warn you about things you should know. By your
logic this code should generate a warning:

short x;

++x;

Semantically, ++x contains an implicit conversion from int to short, which
can result in loss of data.

Same is true about signed/unsigned implicit conversions. Do you want a
warning in this case?

unsigned x;
int y;

x += y;

You're adding a signed int to an unsigned int, that seems so dangerous! You
better cast, that would be so much safer. :)

> > But I might be wrong, so let's say you
> > do get a warning, so you do:
> >
> > void g( int x )
> > {
> > f( static_cast<unsigned>(x) );
> > }
> >
> > How does this help in detecting the logic error of passing a negative x
to
> > g? Can you quantify the exact mechanics by which this cast makes your
code
> > safer? By what measure is the code less safe without the cast?
>
> By itself, it doesn't help; you're correct. But that wasn't what I was
> saying; I was saying that the warning would help you to find that code
> so that you can then rewrite g to one of the following:
>
> void g( unsigned x )
> {
> f(x);
> }
>
> void g( int x )
> {
> assert(x >= 0);
> f(unsigned(x)); // or static_cast, if you prefer
> }

I know, but it is still a valid question to ask what is the role of the
cast. Does it make the program more readable? In what way is your version
preferable?

To me it seems like a potential bug, introduced by a programmer who is
unsure about implicit conversions in C. Semantically, I can't imagine why I
would want the call to f to always cast to unsigned. Consider:

void f( unsigned );
void f( int ); //Later we add this overload

void g( int x )
{
  assert(x>=0);
  f(unsigned(x));
}

> Both of these are correct. Performing conversion (regardless of whether
> it is implicit or explicit) without the assert is incorrect. Performing
> implicit conversion with the assert is safe, but not easily
> distinguishable from the original unsafe code

You keep saying the original code is unsafe. How is the implicit conversion
less safe than the cast?


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