Skip to content

Conversation

@cjbacchus
Copy link

No description provided.

Comment on lines -688 to -689
Plain C-style casts are also **discouraged** in favor of the more expressive
(and easier to recognise and understand) `static_cast`.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can explain better in the text.
The problem of the C-style cast is that it can do any type of harmful things, from truncating a value to removing constancy to stealing your car.
I would recommend the braces-style cast instead as default: unsigned{ 8 } or (unsigned int){ 8 } (yes, that's not what is written in the guideline).

This default will not work when trying to convert:

  • an integer into a floating point; narrowing issues are rare but extremely sneaky; spelling out static_cast() then tells "I know what I am doing"
  • a floating point number to integral; here the rules are clear, but I'd still recommend passing via something more explicit (trunc(), or floor()/ceil() — you do still need a cast though)
  • an integer into a smaller floating point; narrowing issues are rare but extremely sneaky; am I repeating myself?
  • messing with constancy: for that, there is hell const_cast()
  • one type of pointer to another (this is what the other three named casts are trying to improve)

I may be charging too much on the details, but if I assume that people by default use the braces cast (the most harmless), then when I see a different type of cast I "know" they must have put some thought in the choice.
This said, I am not a fan of constructs like:

for (gsl::index i = 0; i < static_cast<gsl::index>(v.size()); ++i) { /* ... */ }

and discouraging is not forbidding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants