Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> 1. because it is greppable and unsafe

But it is not unsafe, or rather, the C++ casts aren't more safe. They have the same semantics.

There are differences casting between class types, but with numeric types the issues are how to handle the value not fitting in (or being imprecise) in the destination type. Casting a value to int in C++ that overflows is still UB.

It doesn't fix C's other strange numeric issues either, like how `unsigned short` * `unsigned short` produces `int`.



C++ casts are safer. I think you are confusing concepts here.

There are C++-style casts that are compile-time errors that C would allow you to do in C style. For C everything is potentially a reinterpret cast basically.

C++ casts are safer than C's.


they are unsafe because if you try to cast something that's not valid the compiler won't let you. you can then choose to ignore it and be unsafe, or figure out the problem and fix it.


You can still cast INT_MAX to short no matter how you spell the cast, and the result won't be correct.


There are more casts than those. Anda reinterpet cast is a superset of a static cast.

If you want to narrow, you would use static cast, not reinterpret cast.

If you want to reinterpret a set of bytes as another object then you reinterpret cast (actuall use std::bit_cast, will catch more errors,). So yes, you can still do that but consciously.

In C you could even turn a cast that is essentially a static cast into a reinterpret cast by accident and the compiler would say nothing.


> If you want to narrow, you would use static cast, not reinterpret cast.

But if you do that, it's not safe! It's the same as C, which is not safe - it's "implementation defined".

Swift would trap on overflow here.


> But if you do that, it's not safe!

static_cast does narrowing foor the case mentioned. reinterpret_cast would just reinterpret the same bit pattern as another type.

Whether it is equivalent or not is another story. For example, casting a float to an int will narrow but also will convert the internal format.

You can catch some overflow by {} initialization.


You shouldn't be using INT_MAX for the last decade or so. That's why std::numeric_limits exist.


You want me to type `std::numeric_limits<int>::max()` in a forum comment? Bit long.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: