0

Given code like the following:

int32_t a = some large value;

int16_t x = a;

I believe that best practices would suggest allowing the compiler to perform an implicit cast from int32_t to int16_t. In my code however I often feel that this is more clear:

int16_t x = static_cast<int16_t>( a );

Is this "correct" or simply verbose? My goal is to ensure that future readers understand the deliberate nature of the truncation.

The reason I ask this question is that my code is filled with tons of explicit casts purely for clarity, which I understand is ill advised.

  • Given that the conversion has implementation-defined behaviour if the value doesn't fit, it seems like an excellent idea to document what's happening and why it is correct. – Kerrek SB Jun 20 '14 at 17:49
  • 1
    I think this is simply a matter of preference. I prefer my casts to be explicit because it shows that it's exactly what you intended. – Joseph Mansfield Jun 20 '14 at 17:49
  • I like explicit cast as well that way when I read your code I understand that you at least thought casting from 32 to 16 bits was the correct thing to do when you wrote the code. Without it and if I'm debugging mentally must stop and can't help suspecting that the implicit cast is causing 'rounding' errors and it will take me longer to find the real issue. – Robert Ekendahl Jun 20 '14 at 19:01
  • _"...which I understand is ill advised."_ Who made you understand that? You should ask them why it was added to the language. You should [show them this](http://stackoverflow.com/questions/103512). – Drew Dormann Jun 20 '14 at 21:18
  • It might also be a good idea to add a comment next to your cast to explain *why* you are performing such a cast. It's one thing a reader of your code seeing you're intending to do a cast and another for them to understand *why* you're doing it. – djikay Jun 20 '14 at 21:42

0 Answers0