Boost logo

Boost :

Subject: Re: [boost] [units] gcc warnings
From: Emil Dotchevski (emil_at_[hidden])
Date: 2010-06-16 12:13:57


On Wed, Jun 16, 2010 at 4:00 AM, Stewart, Robert <Robert.Stewart_at_[hidden]> wrote:
> Emil Dotchevski wrote:
>> Integer implicit conversions specifically are very common in C and
>> C++. For example, incrementing a short int results in two implicit
>> conversions, one of which might lead to truncating the value. That is
>> about as safe (or unsafe) as the code in question, so why nobody cares
>> about that case? Answer: because the compiler doesn't warn.
>
> No, it is because increment has well defined behavior for short that doesn't require a
> warning.  The code in question could have generated -- but doesn't presently -- a
> value that wouldn't fit in the target type leading to a misinterpretation of the result.

AFAIK the semantics of incrementing a short are that its value is
first implicitly converted to int, which is then incremented (as an
int), and then the int result is truncated (assuming
sizeof(short)<sizeof(int)) back to short. As far as warnings are
concerned, shouldn't this be treated identically to the case when the
truncated value was an int to begin with?

>> If you don't want your compiler to issue a particular warning, a type
>> cast should be the last solution to reach for, IMO.
>
> It certainly appears that the types can be adjusted to alleviate the problem in this
> case, but that isn't always possible as impedance mismatches occur that cannot
> be altered.  In such cases, a static_cast, which *should* indicate that the developer
> examined the code in question and has decided that the potential for truncation is
> not an issue

Disabling the warning locally would indicate that the developer
examined the code, but (importantly) the program remains unchanged.
Using static_cast is not the same as disabling the warning locally;
for example, if a future remote edit changes the type of the object
being converted, static_cast may inhibit a compile error.

Even more ill-advised is instead of static_cast<T>(x) to use the
functional notation syntax T(x) which in some cases has the semantics
of a C-style cast which is even more likely to inhibit a compile
error.

Emil Dotchevski
Reverge Studios, Inc.
http://www.revergestudios.com/reblog/index.php?n=ReCode


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